If Statement
An if statement evaluates a variable and executes a block of code assuming the value is valid.
Example
{% if greeting == 1 %}
<h1>Hello</h1>
{% endif %}
Elif
The elif keyword says "on the off chance that the past conditions were false, then attempt this condition".
Example
{% if greeting == 1 %}
<h1>Hello</h1>
{% elif greeting == 2 %}
<h1>Welcome</h1>
{% endif %}
Else
The else keyword finds anything which isn't gotten by the preceding conditions.
Example
{% if greeting == 1 %}
<h1>Hello</h1>
{% elif greeting == 2 %}
<h1>Welcome</h1>
{% else %}
<h1>Goodbye</h1>
{% endif %}
Operators
The above models utilizes the == operator, which is utilized to check if a variable is equivalent to a value, however there are numerous different operators you can utilize, or you could drop the operator if you just want to check if a variable isn't vacant:
Example
{% if greeting %}
<h1>Hello</h1>
{% endif %}
==
Is equal to
Example
{% if greeting == 2 %}
<h1>Hello</h1>
{% endif %}
!=
Is not equal to.
Example
{% if greeting != 1 %}
<h1>Hello</h1>
{% endif %}
<
Is less than
Example
{% if greeting < 3 %}
<h1>Hello</h1>
{% endif %}
<=
Is less than, or equal to.
Example
{% if greeting <= 3 %}
<h1>Hello</h1>
{% endif %}
>
Is greater than
Example
{% if greeting > 1 %}
<h1>Hello</h1>
{% endif %}
>=
Is greater than, or equal to.
Example
{% if greeting >= 1 %}
<h1>Hello</h1>
{% endif %}
and
To check if more than one condition is true.
Example
{% if greeting == 1 and day == "Friday" %}
<h1>Hello Weekend!</h1>
{% endif %}
or
To check if one of the conditions is true.
Example
{% if greeting == 1 or greeting == 5 %}
<h1>Hello</h1>
{% endif %}
and/or
combine and and or
Example
{% if greeting == 1 and day == "Friday" or greeting == 5 %}
in
To check if a certain item is present in an object.
Example
{% if 'Banana' in fruits %}
<h1>Hello</h1>
{% else %}
<h1>Goodbye</h1>
{% endif %}
not in
To check if a certain item is not present in an object.
Example
{% if 'Banana' not in fruits %}
<h1>Hello</h1>
{% else %}
<h1>Goodbye</h1>
{% endif %}
is
Check in the event that two items are something similar.
This operator is not quite the same as the == operator, on the grounds that the == operator really takes a look at the upsides of two items, however the is operator really takes a look at the personality of two items.
In the view we have two articles, x and y, with similar qualities:
Example
views.py
from django.http import HttpResponse
from django.template import loader
def testing(request>
:
template = loader.get_template('template.html'>
context = {
'x': ['Apple', 'Banana', 'Cherry'],
'y': ['Apple', 'Banana', 'Cherry'],
}
return HttpResponse(template.render(context, request>
>
is not
Example
{% if x is not y %}
<h1>YES<h1>
{% else %}
<h1>NO</h1>
{% endif %}