What is the Django Template Language?
Django's template language (DTL) is designed to be simple and readable. It lets you embed dynamic content in HTML without mixing Python code with markup. Templates handle variables, loops, conditionals, and more.
The syntax uses double curly braces for variables and curly braces with percent signs for tags. It's clean, predictable, and easy to learn.
Variables and Output
Use {{ variable }} to output values from your context dictionary. You can access dictionary keys, object attributes, and list items with dot notation.
# View context
context = {
'title': 'My Blog',
'posts': [
{'title': 'First Post', 'author': 'Alice'},
{'title': 'Second Post', 'author': 'Bob'},
]
}
{{ title }}
{{ posts.0.title }}
{{ posts.1.author }}
Django tries dictionary lookups, attribute lookups, and list index lookups in that order. So post.title works whether post is a dictionary with a 'title' key or an object with a title attribute.
Template Tags
Tags do the heavy lifting in templates. They handle logic like conditionals, loops, and URL generation. Tags use the syntax {% tag_name %}.
{% if user.is_authenticated %}
Welcome, {{ user.username }}!
{% else %}
Please log in.
{% endif %}
{% for post in posts %}
{{ post.title }}
{% endfor %}
Tags don't output anything themselves — they control the rendering logic. The output comes from the content between the tags.
Template Inheritance
Template inheritance lets you create a base template with common elements and extend it in child templates. This avoids duplicating headers, footers, and navigation across every page.
{% extends "base.html" %}
{% block content %}
{{ title }}
{{ body }}
{% endblock %}
The {% extends %} tag must be the first template tag in the file. {% block %} defines sections that child templates can override.
Filters
Filters transform variables before output. They're applied with the pipe character and can be chained for multiple transformations.
{{ name|lower }}
{{ title|title }}
{{ date|date:"F j, Y" }}
{{ price|floatformat:2 }}
{{ list|length }}
{{ text|truncatewords:30 }}
{{ name|default:"Anonymous" }}
Filters don't modify the original value — they just change how it's displayed. You can create custom filters in your app's templatetags directory.