Blog available for sell
This blog is available for sale. Please 'contact us' if interested.
Advertise with us
templates   1   48986
Using IF ELSE condition in Django template


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 %}


templates   1   48986
1 comment on 'Using If Else Condition In Django Template'
Login to comment

It Is Not My Name Feb. 4, 2020, 10:33 a.m.
how to use {% if "text" =="text" %} condiciton in django

Related Articles:
How to set a variable in Django template
Declaring a new variable in Django template, Set the value of a variable in Django template, using custom template tag in Django, Defining variables in Django template tag...
How to display flash messages in Django templates
flash messages in Django template, one-time notifications in Django template, messages framework Django, displaying success message in Django, error message display in Django...
5 lesser used Django template tags
rarely used Django template tags, lesser-known Django template tags, 5 awesome Django template tags, Fun with Django template tags,...
Django Template Fiddle Launched !!!!
Django template fiddle, Experimenting with Django templates, Playing with Django template, Django fiddle, template fiddle, djangotemplatefiddle.com,...
DigitalOcean Referral Badge

© 2024-2025 Python Circle   Contact   Sponsor   Archive   Sitemap