In Jinja2 templates, it is often a good practice to test if a variable exists and what value does it carry.
There are several useful tests that you can make using Jinja2 builtin tests and filers.
In this article, i’ll show how to test if a variable exists or not, if it is empty or not and if it is set to True.
I’ll also give two examples of how to combine these checks.
Check Variable in Jinja2
Check if variable is defined (exists):
{% if variable is defined %} variable is defined {% else %} variable is not defined {% endif %}
Check if variable is empty:
{% if variable|length %} variable is not empty {% else %} variable is empty {% endif %}
Check if variable is true:
{% if variable is sameas true %} variable is true {% else %} variable is not true {% endif %}
Check if variable is defined and not empty:
{% if variable is defined and variable|length %} variable is defined and not empty {% else %} variable is not defined or empty {% endif %}
Check if variable is defined and true:
{% if variable is defined and variable is sameas true %} variable is defined and true {% else %} variable is not defined or not set to true {% endif %}
Your third example has a minor mistake. Instead of “variable sameas true” it needs to read “variable is sameas true”. Otherwise, it will throw an error.
Thanks.
Any particular reason why you can’t shorten it to “variable is defined and variable” ?
Hi, can you check if multiple variables are defined?
for example (i don’t know the correct syntax)
{% if variable1, variable2, variable3 %}
{% endif %}
Hi, you can try
{% if variable1 is defined and variable2 is defined and variable3 is defined %}
{% endif %}
Hello – Have a look at: http://jinja.quantprogramming.com/
This template:
foo: {% if foo is defined and foo | length %}{{ foo }}{% else %}””{% endif %}
with this value:
foo:
Produces this result:
Error: tempalate rendering failed. object of type ‘NoneType’ has no len()
But this template:
foo: {% if foo is defined and foo and foo != “” %}{{ foo }}{% else %}””{% endif %}
Works no matter what. I don’t know if that holds true for Jinja everywhere, or if it’s particluar to this online parser
FYI this is exactly what I needed. I was getting the same errors as you when testing against dictionary keys that had no value.
Very useful and the text looks a little like poetry which amuses me. Thanks
Thank you !
thanks!