简体   繁体   English

jinja2 如何检索变量的值以在 if 语句中使用它 jinja2

[英]jinja2 how to retrieve the value of a variable to use it in an if statement jinja2

In order to create a template using jinja and markdown through mkdocs.为了通过 mkdocs 使用 jinja 和 markdown 创建模板。 I met this problem that is blocking me so far.到目前为止,我遇到了这个阻碍我的问题。

I am using a variable in my if statement in order to fill a table with some specific information if the condition is true我在 if 语句中使用了一个变量,以便在条件为真时用一些特定信息填充表格

Let's say that I have different environments (env1 env2 env3) for env1 and env2 the filling of the table doesn't require the if statement to be true but when it comes to env3 the condition must be true so the filling of the table could occur.假设我对 env1 和 env2 有不同的环境(env1 env2 env3),表格的填充不需要 if 语句为真,但是当涉及到 env3 时,条件必须为真,所以表格的填充可能会发生.

My template looks like this我的模板看起来像这样

#{{env}}

##servers

{% if {{env}} = 'env3' %}

|             | IP | FQDN |
|-------------|----|------|
|             |    |      |

{% for node in server.nodes %}|{{node.id}}|{{node.ip}}|{{node.fqdn}}|
{% endfor %} {% for node in server.class.nodes %}|classe{{node.id}}|{{node.ip}}|{{node.fqdn}}|
{% endfor %}

{% else %}

|             | IP | FQDN |
|-------------|----|------|
|  servertype1 | {{server.servertype1.ip}} |      |
|  servertype2 | {{server.servertype2.vip}} |      |
{% for node in server.specific.nodes %}|specific{{node.id}}|{{node.ip}}|{{node.fqdn}}|
{% endfor %} {% for node in server.class.nodes %}|classe{{node.id}}|{{node.ip}}|{{node.fqdn}}|
{% endfor %}
{% endif %}

To resume I am having a hard time to retrieve the value of {{env}} (the one in the title since mkdocs generates it correctly) in order to use it in the if statement so when it comes to the specific page of env3 the table with appropriate info is shown.为了恢复,我很难检索{{env}}的值(标题中的值,因为 mkdocs 正确生成它)以便在 if 语句中使用它,所以当涉及到 env3 的特定页面时显示了包含适当信息的表格。

Here's the error I get:这是我得到的错误:

jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}' jinja2.exceptions.TemplateSyntaxError:预期令牌':',得到'}'

I tried many different variations of the syntax, but the result remains the same.我尝试了许多不同的语法变体,但结果保持不变。

I am welcoming all the leads or hints in order to solve this issue.我欢迎所有线索或提示以解决此问题。

Well I found it !好吧,我找到了!

I just had to adjust my if statement syntax instead of我只需要调整我的 if 语句语法而不是


{% if {{env}} = 'env3' %}

i had to put like this:我不得不这样说:

{% if env == "env3" %}

there was a missing equal sign and quotes instead of ' ' plus the brackets in env i had to delete them缺少等号和引号而不是 ' ' 加上 env 中的括号我不得不删除它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM