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

5 Replies to “Jinja2: Check If Variable – Empty | Exists | Defined | True”

  1. 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.

  2. Any particular reason why you can’t shorten it to “variable is defined and variable” ?

  3. Hi, can you check if multiple variables are defined?
    for example (i don’t know the correct syntax)
    {% if variable1, variable2, variable3 %}

    {% endif %}

  4. Hi, you can try
    {% if variable1 is defined and variable2 is defined and variable3 is defined %}

    {% endif %}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.