Jinja - if else statement
by
Jeremy Canfield |
Updated: September 19 2024
| Jinja articles
An if statement in Jinja has the following structure.
{% if condition %}
<do something>
{% elif condition %}
<do something>
{% else %}
<do something>
{% endif %}
For example.
{% if foo == 'Hello' %}
print("foo equals Hello")
{% elif foo == 'World' %}
print("foo equals World")
{% else %}
print("foo does not equal Hello or World")
{% endif %}
Here is how you would use an or clause.
{% if foo == 'Hello' or foo == 'World' %}
print("foo equals Hello or World")
{% else %}
print("foo does not equal Hello or World")
{% endif %}
Including a single dash after the leading percentage character (%-) and a single dash before the trailing percentage character (-%) should do a trim, removing whitespace from the left and right of the value.
{%- if foo == 'Hello' or foo == 'World' -%}
print(" foo equals Hello or World ")
{%- else -%}
print(" foo does not equal Hello or World ")
{%- endif -%}
Following are command if statements.
if the foo variable is defined | {% if foo %} or {% if foo is defined %} |
if equals | {% if foo == 'Hello' %} |
If not equals | {% if foo != 'Hello' %} |
if contains | {% if foo in 'Hello' %} |
If does not contain | {% if foo not in 'Hello' %} |
If regex | {% if foo | regex_search('^(foo|bar)$', ignorecase=True) %} |
if greater than or less than | {% if 1 < 2 %} |
Did you find this article helpful?
If so, consider buying me a coffee over at