Django Template Tags
Variables print data; tags add logic. A tag is written {% name ... %}, and many tags come in pairs with an end tag such as {% endif %}. Django's template language is intentionally limited — it covers presentation needs (conditions, loops, links) while keeping business logic in Python.
| Tag | Purpose |
|---|---|
{% if %} … {% elif %} … {% else %} … {% endif %} |
conditions |
{% for x in list %} … {% empty %} … {% endfor %} |
loops |
{% comment %} … {% endcomment %} / {# … #} |
comments |
{% url "name" arg %} |
build a URL from a URL name |
{% csrf_token %} |
hidden CSRF field for POST forms |
{% with %} |
local variables |
{% cycle "a" "b" %} |
alternate values in a loop |
{% now "Y" %} |
current date/time |
{% include %}, {% extends %}, {% block %} |
combine templates (next lesson) |
{% load static %} |
load a tag library |
if, elif, else
{% if %} supports and, or, not, comparisons (==, !=, <, >, <=, >=) and in / not in. Empty lists, empty strings, 0 and None count as false:
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context
t = Template("""{% if score >= 90 %}Excellent{% elif score >= 50 %}Passed{% else %}Try again{% endif %}
{% if user and not user.banned %}Welcome back, {{ user.name }}!{% endif %}
{% if "admin" in roles %}[admin tools]{% endif %}{% if not cart %} Cart is empty{% endif %}""")
print(t.render(Context({"score": 95, "user": {"name": "Tien", "banned": False}, "roles": ["admin"], "cart": []})))
print("---")
print(t.render(Context({"score": 61, "user": None, "roles": [], "cart": ["tea"]})))Excellent
Welcome back, Tien!
[admin tools] Cart is empty
---
Passed
for loops
{% for %} iterates over any iterable, including QuerySets. {% empty %} renders when the list is empty, and the forloop variable tells you where you are:
| Variable | Value |
|---|---|
forloop.counter / forloop.counter0 |
position, starting at 1 / 0 |
forloop.revcounter |
items remaining (ending at 1) |
forloop.first / forloop.last |
True on the first / last iteration |
forloop.parentloop |
the enclosing loop's forloop |
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context
t = Template(
"{% for fruit in fruits %}"
"{{ forloop.counter }}. {{ fruit }}{% if forloop.first %} (first){% endif %}"
"{% if not forloop.last %}, {% endif %}"
"{% empty %}No fruit today."
"{% endfor %}"
)
print(t.render(Context({"fruits": ["mango", "lychee", "durian"]})))
print(t.render(Context({"fruits": []})))
t2 = Template("{% for name, price in prices.items %}{{ name }}={{ price }} {% endfor %}")
print(t2.render(Context({"prices": {"pho": 50, "banh mi": 25}})))
t3 = Template("{% for n in nums reversed %}{% cycle 'odd' 'even' %}:{{ n }} {% endfor %}")
print(t3.render(Context({"nums": [1, 2, 3, 4]})))1. mango (first), 2. lychee, 3. durian
No fruit today.
pho=50 banh mi=25
odd:4 even:3 odd:2 even:1
Note {% for key, value in dict.items %} — items is called automatically, without parentheses.
Looping over a QuerySet
Tags work with database results directly. Here a view passes a QuerySet and the template groups output with forloop:
import sys, types, django
from django.conf import settings
sys.modules["urls"] = urls = types.ModuleType("urls")
settings.configure(
SECRET_KEY="demo", ROOT_URLCONF="urls", ALLOWED_HOSTS=["testserver"],
DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates",
"OPTIONS": {"loaders": [("django.template.loaders.locmem.Loader", {
"tasks.html": """<ul>
{% for task in tasks %} <li>{% if task.done %}<s>{{ task.title }}</s>{% else %}{{ task.title }}{% endif %}</li>
{% empty %} <li>Nothing to do</li>
{% endfor %}</ul>
{{ tasks|length }} task{{ tasks|length|pluralize }}""",
})]}}],
)
django.setup()
from django.db import models, connection
from django.shortcuts import render
from django.urls import path
from django.test import Client
class Task(models.Model):
title = models.CharField(max_length=50)
done = models.BooleanField(default=False)
class Meta:
app_label = "demo"
with connection.schema_editor() as editor:
editor.create_model(Task)
Task.objects.create(title="Water plants", done=True)
Task.objects.create(title="Write report")
def task_list(request):
return render(request, "tasks.html", {"tasks": Task.objects.order_by("id")})
urls.urlpatterns = [path("", task_list)]
print(Client().get("/").content.decode())<ul>
<li><s>Water plants</s></li>
<li>Write report</li>
</ul>
2 tasks
Comments
Single-line comments use {# … #}; multi-line comments use the comment block. Neither appears in the output:
import django
from django.conf import settings
settings.configure(TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates"}])
django.setup()
from django.template import Template, Context
t = Template("""Visible {# hidden note #}text
{% comment "why it's disabled" %}
<p>Old banner: {{ banner }}</p>
{% endcomment %}End""")
print(t.render(Context({"banner": "SALE"})))Visible text
End
Note: An HTML comment
<!-- … -->is not a template comment: it's sent to the browser, and any{{ variables }}inside it are still rendered.
url and csrf_token
Two tags appear in almost every real form. {% url %} builds a link from a URL name (see URLs), and {% csrf_token %} inserts a hidden field that protects POST forms:
<form method="post" action="{% url 'book_create' %}">
{% csrf_token %}
<input name="title">
<button>Save</button>
</form>
<a href="{% url 'book_detail' book.pk %}">{{ book.title }}</a>Test yourself
Which tag renders content when a {% for %} loop has nothing to iterate over?
- {% else %}
- {% empty %}
- {% none %}
- {% default %}
Which variable is True only on the last iteration of a loop?
- forloop.end
- forloop.last
- loop.last
- forloop.final
How do you write a single-line template comment?
- <!-- note -->
- {# note #}
- {% # note %}
- // note