0
0
DjangoHow-ToBeginner · 3 min read

How to Use If Else in Django Template: Syntax and Examples

In Django templates, use the {% if %} tag to check a condition and {% else %} for the alternative case. Wrap the content to show inside these tags, and close with {% endif %} to complete the conditional block.
📐

Syntax

The {% if %} tag evaluates a condition. If true, it renders the content inside it. The {% else %} tag defines what to render if the condition is false. Always close the block with {% endif %}.

  • {% if condition %}: Start the condition.
  • {% else %}: Optional, runs if condition is false.
  • {% endif %}: Ends the if block.
django
{% if user.is_authenticated %}
  <p>Welcome, {{ user.username }}!</p>
{% else %}
  <p>Please log in.</p>
{% endif %}
💻

Example

This example shows how to greet a user if they are logged in, or ask them to log in if not.

django
{% if user.is_authenticated %}
  <p>Welcome, {{ user.username }}!</p>
{% else %}
  <p>Please log in.</p>
{% endif %}
Output
<p>Welcome, alice!</p> (if user is logged in as alice) <p>Please log in.</p> (if user is not logged in)
⚠️

Common Pitfalls

Common mistakes include forgetting to close the {% if %} block with {% endif %}, or using Python syntax like elif instead of Django's {% elif %}. Also, ensure the condition is valid and variables exist in the template context.

django
{% if user.is_authenticated %}
  <p>Welcome!</p>
{% elif user.is_staff %}  <!-- Correct: use {% elif %} not Python elif -->
  <p>Staff member</p>
{% else %}
  <p>Please log in.</p>
{% endif %}
📊

Quick Reference

TagPurpose
{% if condition %}Start a conditional block
{% elif condition %}Check another condition if previous was false
{% else %}Fallback if all conditions are false
{% endif %}End the conditional block

Key Takeaways

Use {% if %} and {% else %} tags to control what content shows based on conditions.
Always close your if blocks with {% endif %} to avoid template errors.
Use {% elif %} for multiple conditions instead of Python's elif syntax.
Ensure variables used in conditions exist in the template context.
Django template tags differ from Python syntax; follow Django's tag rules.