Jinja2 if Statement
n
n
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.
nn
n
Basic
Basic if Statement
n
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.
nn
n{% if users %} Users found.n{% for user in users %}n{{ user.username|e }}n{% endfor %}n{% endif %}n
n
nn
n
`if…else` and `elif`
n
Use an `else` block to provide an alternative if the initial condition is false. For multiple conditions, chain them with `elif`.
nn
{% if user.is_authenticated %}nWelcome, {{ user.username }}!n{% else %}nPlease log in.n{% endif %} {# Multiple conditions with elif #} {% if user.role == 'admin' %}nAdmin dashboard.n{% elif user.role == 'editor' %}nEditor tools.n{% else %}nUser profile.n{% endif %}n
n
nn
n
Common Tests and Operators
n
You can combine conditions using logical operators (`and`, `or`, `not`) and use the `is` operator with built-in tests like `defined`, `none`, and `empty`.
nn
{% if my_variable is defined and my_variable is not none %}nThe variable is defined and has a value.n{% endif %} {# Check if a list or string is empty #} {% if articles is empty %}nNo articles to display.n{% endif %} {# Combining conditions #} {% if user.is_authenticated and user.country == 'US' %}nUS-specific content.n{% endif %}n
n
n
