In Jinja2, how do you test if a variable is undefined?

freyley picture freyley · Oct 1, 2010 · Viewed 200k times · Source

Converting from Django, I'm used to doing something like this:

{% if not var1 %} {% endif %}

and having it work if I didn't put var1 into the context. Jinja2 gives me an undefined error. Is there an easy way to say {% if var1 == None %} or similar?

Answer

Garrett picture Garrett · Oct 1, 2010

From the Jinja2 template designer documentation:

{% if variable is defined %}
    value of variable: {{ variable }}
{% else %}
    variable is not defined
{% endif %}