if Template Tag
Example
Display a header if the value of the myvar
variable is 1:
{% if myvar == 1 %}
<h1>Hello!</h1>
{% endif %}
Run Example »
Definition and Usage
The if
tag allows you to write conditional statements.
Use if
statements to output a block of code
if a condition is true.
You can use else
or
elif
(short for "else if") to specify what to
do when the if
condition is false.
Example
Display one heading if myvar
is 1, and
another if myvar
is 2:
{% if myvar == 1 %}
<h1>Hello!</h1>
{% else %}
<h1>Greetings!</h1>
{% endif %}
Run Example »
Example
Display a third heading if none of the conditions are true:
{% if myvar == 1 %}
<h1>Hello!</h1>
{% elif myvar == 2 %}
<h1>Welcome!</h1>
{% else %}
<h1>Greetings!</h1>
{% endif %}
Run Example »
Syntax
{% if condition %}
...
{% endif %}
Parameters
Value | Description |
---|---|
condition | Required. Anything that evaluates to either true or false. |
Operators
There are some built-in operators you can use when evaluating
if
statements:
Variable | Description | |
---|---|---|
== | is equal to | Example » |
!= | is not equal to | Example » |
< | is less than | Example » |
<= | is less than, or equal to | Example » |
> | is greater than | Example » |
>= | is greater than, or equal to | Example » |
and | condition1 and condition2 must be true | Example » |
or | condition1 or condition2 must be true | Example » |
in | an item must be present in an object | Example » |
is | is the same value as | Example » |
is not | is not the same value as | Example » |
not in | is not in | Example » |