Django Template Tag Reference

Complete guide to Django's built-in template tags

🏷️ What are Template Tags?

Template tags are special syntax in Django templates that perform logic operations like loops, conditionals, and variable manipulation. They enable dynamic content generation using {% tag %} syntax for powerful template functionality.


<!-- Basic template tag usage -->
{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% endif %}
                                    

Common Template Tags

🔁

for

Loop through lists and querysets

{% for item in items %}
  <p>{{ item }}</p>
{% endfor %}

if

Conditional logic in templates

{% if user.is_staff %}
  <p>Admin</p>
{% endif %}
🧩

block

Define template inheritance blocks

{% block content %}
  Default content
{% endblock %}
📥

include

Include other templates

{% include 'header.html' %}

🔹 for - Loop Tag

The for tag loops over items in a sequence like lists, tuples, or querysets. It provides special variables like forloop.counter and forloop.first for enhanced control.

<!-- Basic for loop -->
{% for product in products %}
    <div>{{ product.name }} - ${{ product.price }}</div>
{% endfor %}

<!-- With forloop variables -->
{% for item in items %}
    <p>{{ forloop.counter }}. {{ item }}</p>
{% endfor %}

<!-- With empty clause -->
{% for user in users %}
    <li>{{ user.username }}</li>
{% empty %}
    <li>No users found</li>
{% endfor %}

<!-- Reversed loop -->
{% for num in numbers reversed %}
    <span>{{ num }}</span>
{% endfor %}

forloop Variables:

  • forloop.counter - Current iteration (1-indexed)
  • forloop.counter0 - Current iteration (0-indexed)
  • forloop.first - True on first iteration
  • forloop.last - True on last iteration
  • forloop.parentloop - Parent loop in nested loops

🔹 if/elif/else - Conditional Tags

Conditional tags allow you to display content based on conditions. Supports comparison operators, logical operators, and membership tests for flexible template logic.

<!-- Basic if statement -->
{% if user.is_authenticated %}
    <p>Welcome back!</p>
{% endif %}

<!-- if/else -->
{% if score >= 90 %}
    <p>Grade: A</p>
{% else %}
    <p>Grade: B or lower</p>
{% endif %}

<!-- if/elif/else -->
{% if temperature > 30 %}
    <p>It's hot!</p>
{% elif temperature > 20 %}
    <p>It's warm</p>
{% else %}
    <p>It's cold</p>
{% endif %}

<!-- Logical operators -->
{% if user.is_authenticated and user.is_staff %}
    <a href="/admin/">Admin Panel</a>
{% endif %}

{% if product.on_sale or product.featured %}
    <span class="badge">Special</span>
{% endif %}

🔹 block/extends - Template Inheritance

Template inheritance lets you build a base template with blocks that child templates can override. This promotes code reuse and maintains consistent layouts across pages.

<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
    <header>
        {% block header %}
            <h1>Default Header</h1>
        {% endblock %}
    </header>
    
    <main>
        {% block content %}
        {% endblock %}
    </main>
    
    <footer>
        {% block footer %}
            <p>© 2025</p>
        {% endblock %}
    </footer>
</body>
</html>

<!-- home.html -->
{% extends 'base.html' %}

{% block title %}Home - My Site{% endblock %}

{% block content %}
    <h2>Welcome to the homepage!</h2>
    <p>This content replaces the block.</p>
{% endblock %}

🔹 include - Include Templates

The include tag loads and renders another template with the current context. Useful for reusable components like headers, footers, and navigation menus.

<!-- main.html -->
{% include 'navbar.html' %}

<div class="content">
    <h1>Main Content</h1>
</div>

{% include 'footer.html' %}

<!-- Include with variables -->
{% include 'card.html' with title="Product" price=29.99 %}

<!-- Include with only specific context -->
{% include 'widget.html' with name=user.name only %}
<!-- navbar.html -->
<nav>
    <a href="/">Home</a>
    {% if user.is_authenticated %}
        <a href="/profile/">Profile</a>
        <a href="/logout/">Logout</a>
    {% else %}
        <a href="/login/">Login</a>
    {% endif %}
</nav>

🔹 url - URL Reversing

The url tag generates URLs by reversing URL patterns defined in urls.py. This keeps your templates independent of URL structure changes.

# urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name='home'),
    path('post/<int:pk>/', views.post_detail, name='post_detail'),
    path('category/<slug:slug>/', views.category, name='category'),
]
<!-- template.html -->
<!-- Simple URL -->
<a href="{% url 'home' %}">Home</a>

<!-- URL with arguments -->
<a href="{% url 'post_detail' pk=post.id %}">Read More</a>

<!-- URL with slug -->
<a href="{% url 'category' slug='technology' %}">Tech Posts</a>

<!-- URL as variable -->
{% url 'post_detail' pk=post.id as post_url %}
<a href="{{ post_url }}">{{ post.title }}</a>

🔹 with - Variable Assignment

The with tag creates temporary variables in templates to simplify complex expressions and improve readability by caching expensive operations.

<!-- Cache complex expression -->
{% with total=business.employees.count %}
    <p>Total employees: {{ total }}</p>
    {% if total > 100 %}
        <p>Large company</p>
    {% endif %}
{% endwith %}

<!-- Multiple variables -->
{% with alpha=1 beta=2 %}
    <p>Sum: {{ alpha|add:beta }}</p>
{% endwith %}

<!-- Simplify long variable names -->
{% with user_profile=request.user.profile %}
    <p>{{ user_profile.bio }}</p>
    <img src="{{ user_profile.avatar.url }}">
{% endwith %}

🔹 csrf_token - CSRF Protection

The csrf_token tag adds Cross-Site Request Forgery protection to forms. Required for all POST, PUT, PATCH, and DELETE requests in Django.

<!-- Basic form with CSRF -->
<form method="post" action="/submit/">
    {% csrf_token %}
    <input type="text" name="username">
    <button type="submit">Submit</button>
</form>

<!-- AJAX with CSRF token -->
<script>
const csrftoken = '{{ csrf_token }}';
fetch('/api/data/', {
    method: 'POST',
    headers: {
        'X-CSRFToken': csrftoken,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({data: 'value'})
});
</script>

🔹 static - Static Files

The static tag generates URLs for static files like CSS, JavaScript, and images. Automatically handles STATIC_URL configuration from settings.

<!-- Load static tag library -->
{% load static %}

<!-- Link CSS file -->
<link rel="stylesheet" href="{% static 'css/style.css' %}">

<!-- Load JavaScript -->
<script src="{% static 'js/app.js' %}"></script>

<!-- Display image -->
<img src="{% static 'images/logo.png' %}" alt="Logo">

<!-- Store URL in variable -->
{% static 'images/banner.jpg' as banner_url %}
<div style="background-image: url('{{ banner_url }}');"></div>

🔹 now - Current Date/Time

The now tag displays the current date and time with customizable formatting. Useful for timestamps, copyright years, and dynamic date displays.

<!-- Current year -->
<p>© {% now "Y" %} My Company</p>

<!-- Full date and time -->
<p>Generated: {% now "F j, Y, g:i a" %}</p>

<!-- Short date -->
<p>Today: {% now "m/d/Y" %}</p>

<!-- Day of week -->
<p>{% now "l" %}</p>

<!-- Custom format -->
<p>{% now "jS F Y" %}</p>

Output Examples:

© 2025 My Company

Generated: January 15, 2024, 3:45 p.m.

Today: 01/15/2024

Monday

15th January 2024

🔹 comment - Template Comments

The comment tag allows multi-line comments in templates that won't appear in rendered HTML. Useful for documentation and temporarily disabling code.

<!-- Single line comment -->
{# This is a single-line comment #}

<!-- Multi-line comment -->
{% comment %}
This is a multi-line comment.
It can span multiple lines.
Useful for documentation.
{% endcomment %}

<!-- Comment with reason -->
{% comment "Disabled for testing" %}
<div class="feature">
    <p>This feature is temporarily disabled</p>
</div>
{% endcomment %}

🔹 autoescape - Control Auto-escaping

The autoescape tag controls automatic HTML escaping in template sections. Use carefully to prevent XSS vulnerabilities when displaying user-generated content.

<!-- Auto-escaping ON (default) -->
{% autoescape on %}
    {{ user_input }}  <!-- HTML will be escaped -->
{% endautoescape %}

<!-- Auto-escaping OFF (use with caution) -->
{% autoescape off %}
    {{ trusted_html }}  <!-- HTML will render -->
{% endautoescape %}

<!-- Example -->
{% autoescape on %}
    <p>{{ comment }}</p>  <!-- <script> becomes &lt;script&gt; -->
{% endautoescape %}

🔹 load - Load Template Libraries

The load tag imports custom template tag libraries and filters. Required before using static, humanize, or custom template tags in your templates.

<!-- Load static files -->
{% load static %}
<img src="{% static 'logo.png' %}">

<!-- Load humanize filters -->
{% load humanize %}
<p>{{ number|intcomma }}</p>

<!-- Load custom tags -->
{% load custom_tags %}
{% my_custom_tag %}

<!-- Load multiple libraries -->
{% load static humanize custom_tags %}

🔹 Template Tag Summary

Essential Template Tags:

  • {% for %} - Loop through sequences
  • {% if %} - Conditional logic
  • {% block %} - Template inheritance
  • {% extends %} - Inherit from base template
  • {% include %} - Include other templates
  • {% url %} - Reverse URL patterns
  • {% static %} - Link static files
  • {% csrf_token %} - CSRF protection
  • {% with %} - Create temporary variables
  • {% load %} - Load template libraries

🧠 Test Your Knowledge

Which tag is used to inherit from a base template?