'if' statement in jinja2 template

PythonTemplatesJinja2

Python Problem Overview


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'

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionLuisitoView Question on Stackoverflow
Solution 1 - PythonNickView Answer on Stackoverflow
Solution 2 - PythonMichel FernandesView Answer on Stackoverflow