Django Template If Else
The {% if %} tag lets templates render different HTML depending on truthiness or comparisons of a context variable.
The {% if %} Tag
{% if %} evaluates a variable or expression for truthiness, exactly like Python's if statement, but without parentheses or a colon. Content inside the tag renders only when the condition is true, and the block must be explicitly closed with {% endif %}.
Example
{% if user.is_authenticated %}
<p>Welcome back, {{ user.username }}!</p>
{% endif %}else and elif for Multiple Branches
A single if can chain additional conditions with {% elif %} and provide a fallback with {% else %}. Django checks each condition top to bottom and renders the first branch that matches, falling through to else only if none of them do.
Example
{% if cart.total >= 100 %}
<p>You qualify for free shipping!</p>
{% elif cart.total >= 50 %}
<p>Spend a little more to unlock free shipping.</p>
{% else %}
<p>Add items to your cart to see offers.</p>
{% endif %}Example
{% if role == 'admin' or role == 'editor' %}
<p>You can publish articles.</p>
{% endif %}
{% if 'draft' not in article.tags and article.published %}
<p>This article is live.</p>
{% endif %}
{% if not user.is_authenticated %}
<a href="{% url 'login' %}">Log in</a>
{% endif %}Django template conditions support ==, !=, <, >, <=, >=, in, not in, and, or, and not. Truthiness follows normal Python rules: an empty string, empty list, 0, None, and False are all falsy, so {% if articles %} is a safe way to check for a non-empty queryset before looping over it.
- == and != — equality and inequality
- <, >, <=, >= — numeric and date comparisons
- in and not in — membership tests against a list, string, or queryset
- and, or, not — combine or negate conditions
Exercise: Django Template If Else
Which tag must close an if block in a Django template?