1000 Python Questions
Get 1 Python question daily. Join this telegram channel https://t.me/python1000questions
Advertise with us
templates   1   15849
Using IF ELSE condition in Django template

The generic syntax of IF ELSE condition is as below:

if condition:
    do this
    do that

Python syntax is almost the same as the pseudo-code written above. 

if 2 > 1:
print('condition is true')
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 %}
{% 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:

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   15849

Related Articles:
For loop in Django template
using for loop in Django templates, Using break in Django template for loop, Using range in django template for loop, How to access index in for loop in django template, for - empty in django template...
Django Template Fiddle Launched !!!!
Django template fiddle, Experimenting with Django templates, Playing with Django template, Django fiddle, template fiddle, djangotemplatefiddle.com,...
Solving Django Error: TemplateDoesNotExist at /app_name/
How to solve TemplateDoesNotExist error in Django projects, reason for TemplateDoesNotExist error in Django, fixing TemplateDoesNotExist error 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,...

1 thought on 'Using If Else Condition In Django Template'
It Is Not My Name :
how to use {% if "text" =="text" %} condiciton in django

Leave a comment:

*All Fields are mandatory. **Email Id will not be published publicly.

Please subscribe to get the latest articles in your mailbox.

© 2017-2020 Python Circle   Contact   Sponsor   Archive   Sitemap