Control Flow Tags
Django provides several tags for controlling the flow of your templates. The most common are {% if %} and {% for %}. These let you add logic directly in your templates without writing Python code.
{% if user.is_superuser %}
Admin Panel
{% elif user.is_authenticated %}
Dashboard
{% else %}
Login
{% endif %}
The {% if %} tag supports elif and else blocks. You can use complex conditions with and, or, and not.
Looping with for
The {% for %} tag iterates over lists and querysets. It provides loop variables like forloop.counter, forloop.first, and forloop.last.
{% for item in items %}
{{ forloop.counter }}. {{ item.name }}
{% if forloop.last %}
That's all!
{% endif %}
{% empty %}
No items found.
{% endfor %}
The {% empty %} block handles empty lists gracefully. Always use it instead of checking forloop.length.
URL and Static Tags
The {% url %} tag reverses URL names into actual URLs. The {% static %} tag generates URLs for static files like CSS, JavaScript, and images.
{% url 'post_detail' post_id=post.id %}
{% url 'user_profile' username=user.username %}
{% static 'css/style.css' %}
{% static 'images/logo.png' %}
Never hardcode URLs in templates. Always use the {% url %} tag so your links stay valid when you change URL patterns.
Include and Block Tags
The {% include %} tag loads another template inside the current one. The {% block %} tag defines overridable sections for template inheritance.
{% include "navbar.html" %}
{% include "sidebar.html" with title="Menu" %}
{% block content %}
Default content here.
{% endblock %}
{% include %} is perfect for reusable components like headers, footers, and navigation bars. The included template inherits the current context.
Advanced Tags
Django offers several powerful tags for complex template logic. {% with %} creates temporary variables. {% regroup %} groups list items. {% load %} imports custom tag libraries.
{% with total=items|length %}
{{ total }} items found.
{% endwith %}
{% regroup cities by country as country_list %}
{% for country in country_list %}
{{ country.grouper }}
{% for city in country.list %}
{{ city.name }}
{% endfor %}
{% endfor %}
{% load static %}
{% load cache %}
{% with %} improves readability when you use a variable multiple times. {% regroup %} is essential for grouping data from your view.