The generic syntax of IF ELSE
condition is as below:
if condition: do this else: do that
Python syntax is almost the same as the pseudo-code written above.
if 2 > 1:
print('condition is true')
else:
print('condition is false')
IF ELSE
syntax for the Django template is slightly different. If
is the builtin tag in Django templates. The basic syntax is:
{% if is_user_logged_in %}
<div>Hello {{username}}</div>
{% else %}
<div>Hello</div>
{% endif %}
IF
tag evaluates the variable and variable is considered True
if it exists and is not empty (if that variable is any iterable) and is not a False boolean value. Which means we can use a boolean variable, a list or a set with IF
tag.
For example:
mylist = [] if mylist: print("true") else: print("false")
will print false
.
We can use multiple elif
with IF
tag.
{% if user_type == "admin" %}
<div>Welcome {{user}}</div>
{% elif user_type == "developer" %}
<div>Hello {{user}}</div>
{% elif user_type == "QA" %}
<div>Hi {{user}}</div>
{% else %}
<div>Greetings {{user}}</div>
{% endif %}
Any combination of and
, or
and not
can be used. and
is given a higher priority than or
.
{% if condition_1 and condition_2 or condition_3 %}
in
operator can be used as below.
{% if user in vip_user_list %}
Filters can also be used in IF
condition.
{% if message|length > 100 %} <a href="">View More</a> {% else %} {{ message }} {% endif %}