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

Viewed 291235

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?

8 Answers

I had an issue like this in Ansible. Ended up having to do a test on both @Garret and @Carsten / @azalea answers, so:

{% if variable is defined and variable %}
    value of variable: {{ variable }}
{% else %}
    variable is not defined or is falsy
{% endif %}
Related