42
votes

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'

2
is should be used when comparing to a type, e.g. if var is list. In your case you want key == 'priority'. - Nicole White
@NicoleWhite In python the test if var is list does not check if var is a list ... it checks if var is the exact type list ... in jinja2, if var is list looks for a test named list ... which is unlikely to exist at all!! - donkopotamus
Sorry, meant type(var) is list. - Nicole White

2 Answers

64
votes

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.

41
votes

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