Menu
Jinja If: basic if statement – Jinja Documentation

Jinja If: basic if statement

Jinja2ifStatement

The Jinja2 if statement is a fundamental control structure for conditional logic in templates. It allows you to selectively render content based on whether a condition is true or false. In Jinja2, a variable is considered "truthy" if it's defined and not empty.

BasicifStatement

The most common use case is to check if a variable has a value. The code inside the block will only render if the variable is not empty, such as a non-empty list or string.

text

{% if users %} Users found.
{% for user in users %}
{{ user.username|e }}
{% endfor %}
{% endif %}

`if...else` and `elif`

Use an `else` block to provide an alternative if the initial condition is false. For multiple conditions, chain them with `elif`.

text
{% if user.is_authenticated %}
Welcome, {{ user.username }}!
{% else %}
Please log in.
{% endif %}  {% if user.role == 'admin' %}
Admin dashboard.
{% elif user.role == 'editor' %}
Editor tools.
{% else %}
User profile.
{% endif %}

Common Tests and Operators

You can combine conditions using logical operators (`and`, `or`, `not`) and use the `is` operator with built-in tests like `defined`, `none`, and `empty`.

text
{% if my_variable is defined and my_variable is not none %}
The variable is defined and has a value.
{% endif %}  {% if articles is empty %}
No articles to display.
{% endif %}  {% if user.is_authenticated and user.country == 'US' %}
US-specific content.
{% endif %}