84

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'

Andrzej Sydor
  • 1,373
  • 4
  • 13
  • 28
Luisito
  • 895
  • 1
  • 7
  • 9
  • 3
    `is` should be used when comparing to a type, e.g. `if var is list`. In your case you want `key == 'priority'`. – Nicole White Nov 15 '16 at 22:42
  • @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 Nov 15 '16 at 22:46
  • 1
    Sorry, meant `type(var) is list`. – Nicole White Nov 15 '16 at 22:49

2 Answers2

119

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.

Nick
  • 7,103
  • 2
  • 21
  • 43
  • I've downvoted for now, there is no need for the quotes around Priority, or the `str` inside the `{{ }}`. i.e. it should just be `

    Priority: {{ data["priority"] }}

    `
    – donkopotamus Nov 15 '16 at 22:37
  • 8
    worth adding minus after percent sign `{%- if 'a' in data -%}` to avoid empty lines – Lukasz Sep 30 '20 at 13:38
66

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 %}
Sylhare
  • 5,907
  • 8
  • 64
  • 80
Michel Fernandes
  • 1,187
  • 9
  • 8