'if' statement in jinja2 template

Question:

I’m trying to write an if statement in jinja template:

{% for key in data %}
    {% if key is 'priority' %}
        <p>('Priority: ' + str(data[key])</p>
    {% endif %}
{% endfor %}

the statement I’m trying to translate in Python is:

if key == priority:
    print(print('Priority: ' + str(data[key]))

This is the error i’m getting:

TemplateSyntaxError: expected token ‘name’, got ‘string’

Asked By: Luisito

||

Answers:

Why the loop?

You could simply do this:

{% if 'priority' in data %}
    <p>Priority: {{ data['priority'] }}</p>
{% endif %}

When you were originally doing your string comparison, you should have used == instead.

Answered By: Nick

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}
Answered By: Michel Fernandes
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.