Jinja2: Check If Variable – Empty | Exists | Defined | True

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