django template using if...elif...else¶
We can use if...elif..else conditionals in django template. The only difference between python code and django template code is it's syntax. It's similar to python code.
Django template "if" syntax:¶
{% if <condition> %}
{{<variable>}}
{% endif %}
Django template "if..else" syntax:¶
{% if <condition> %}
{{<variable1>}}
{% else %}
{{<variable2>}}
{% endif %}
Django template "if..elif..else" syntax:¶
{% if <condition1> %}
{{<variable1>}}
{% elif <condition2> %}
{{<variable2>}}
{% else %}
{{<variable3>}}
{% endif %}
Notes on django template conditionals (if...elif...else)¶
- If you do not write syntax correctly then django will throw errors.
- Do not use object method calls using parenthesis (i.e "()") just use method name instead.
- We can write multiple if..elif..else conditionals.
- We can write any number of "if...elif...else" nested conditionals in django templates.
- We can use operators like "and", "or", "in", "==", "<", ">", etc.
- Evaluation takes from left to right.
Examples for django template if...elif...else conditionals¶
{% if athlete_list %}
Number of athletes: {{ athlete_list|length }}
{% elif athlete_in_locker_room_list %}
Athletes should be out of the locker room soon!
{% else %}
No athletes.
{% endif %}
{% if athlete_list and coach_list %}
Both athletes and coaches are available.
{% endif %}
{% if not athlete_list %}
There are no athletes.
{% endif %}
{% if athlete_list or coach_list %}
There are some athletes or some coaches.
{% endif %}
{% if not athlete_list or coach_list %}
There are no athletes or there are some coaches.
{% endif %}
{% if athlete_list and not coach_list %}
There are some athletes and absolutely no coaches.
{% endif %}