Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
584 views
in Technique[技术] by (71.8m points)

markdown - 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. 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

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.

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.

Here's the error I get :

jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'

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.

question from:https://stackoverflow.com/questions/65885973/jinja2-how-to-retrieve-the-value-of-a-variable-to-use-it-in-an-if-statement-jinj

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well I found it !

I just had to adjust my if statement syntax instead of


{% 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...