Chapter 5 · 10 min read
Templates
Templates
Returning strings from views does not scale. Real pages are HTML, and mixing HTML into Python is messy. Django's answer is the template: an HTML file with small placeholders that Django fills in.
What you will learn
- How to render a template from a view with
render(). - The Django Template Language: variables, tags and filters.
- How to reuse a page layout with template inheritance.
- Why Django escapes HTML automatically.
- How template partials (new in Django 6.0) work.
The three kinds of template syntax
| Syntax | Purpose | Example |
|---|---|---|
{{ variable }} | Print a value | {{ site_name }} |
{% tag %} | Run logic such as loops and conditions | {% for topic in topics %} |
{{ value|filter }} | Change how a value is displayed | {{ name|upper }} |
A view passes data to a template in a dictionary called the context. Each key becomes a variable in the template.
Where templates live
Create a folder blog/templates/blog/. The repeated blog/ is intentional. Django merges the templates folders of all installed apps into one search path, so two apps that both have home.html would clash. The inner folder acts as a namespace: you ask for blog/home.html.
Step by step
1. The base layout
Create blog/templates/blog/base.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{% block title %}My Blog{% endblock %}</title>
</head>
<body>
<nav><a href="{% url 'blog:home' %}">Home</a></nav>
<main>{% block content %}{% endblock %}</main>
</body>
</html>
The block tags mark areas that child templates may replace. The url tag turns the name blog:home into the real address, so if you later move the page, the link updates itself.
2. A child template
Create blog/templates/blog/home.html:
{% extends "blog/base.html" %}
{% block title %}Home{% endblock %}
{% block content %}
<h1>Welcome to {{ site_name }}</h1>
<ul>
{% for topic in topics %}
<li>{{ forloop.counter }}. {{ topic|upper }}</li>
{% empty %}
<li>No topics yet.</li>
{% endfor %}
</ul>
{% endblock %}
{% extends %}must be the first tag. It says this page is built onbase.html.- Each
{% block %}replaces the block with the same name in the parent. forloop.countercounts from 1.{% empty %}runs when the list has no items.topic|upperapplies theupperfilter.
3. Render it from the view
Update blog/views.py:
from django.http import HttpResponse
from django.shortcuts import render
def home(request):
context = {"site_name": "My Blog", "topics": ["Python", "Django", "HTML"]}
return render(request, "blog/home.html", context)
def hello(request, name):
return HttpResponse(f"Hello, {name}!")
render(request, template_name, context) loads the template, fills it with the context and returns an HttpResponse.
Common tags and filters
| Tag | What it does |
|---|---|
{% if %}, {% elif %}, {% else %}, {% endif %} | Conditions |
{% for x in list %} ... {% empty %} ... {% endfor %} | Loops |
{% url 'name' arg %} | Reverse a URL |
{% include "file.html" %} | Insert another template |
{% load static %} | Load the static tag library |
{% csrf_token %} | Add the security token to forms |
| Filter | Example result |
|---|---|
upper, lower, title | Change letter case |
truncatewords:30 | Cut text after 30 words |
date:"j M Y" | Format a date such as 2 Dec 2026 |
linebreaks | Turn blank lines into paragraphs |
default:"none" | Show a fallback for empty values |
length | Count items |
Dots: variable lookups
Inside {{ }} a dot looks up an attribute, a dictionary key, a list index, or calls a method with no arguments. So {{ post.author.username }} follows the object chain, and {{ topics.0 }} is the first list item.
Automatic escaping
Django replaces characters such as < and > in variables with safe HTML entities. If a user types a script tag as their name, the page shows it as harmless text instead of running it. This protects you from cross-site scripting (XSS). The filter safe switches escaping off. Never use it on anything a user typed.
Template partials (new in Django 6.0)
Django 6.0 added partials: named fragments inside a template file. You define one with {% partialdef name %} ... {% endpartialdef %} and print it with {% partial name %}:
{% partialdef topic_item %}<li>{{ topic }}</li>{% endpartialdef %}
<ul>
{% for topic in topics %}{% partial topic_item %}{% endfor %}
</ul>
Partials help when a small piece repeats, or when a view wants to render just one fragment. The official documentation also describes the template_name#partial_name form for loading a partial directly. Try the example above as an optional experiment in home.html.
Check it works
- http://127.0.0.1:8000/ shows
Welcome to My Blogand a numbered list in capital letters. - In the browser, choose View Source: the page is plain HTML and contains no template tags.
Exercises with solutions
Exercise 1: an about template
Create about.html that extends base.html, with a view and URL, and a link in the navigation.
Solution. Template blog/templates/blog/about.html:
{% extends "blog/base.html" %}
{% block title %}About{% endblock %}
{% block content %}
<h1>About</h1>
<p>I am learning Django 6.1.</p>
{% endblock %}
View:
def about(request):
return render(request, "blog/about.html")
URL: path("about/", views.about, name="about"),. In base.html's <nav> add <a href="{% url 'blog:about' %}">About</a>.
Exercise 2: the empty case
Set topics to an empty list in the view and reload.
Solution. The page shows No topics yet. because the {% empty %} branch of the loop runs. Put the list back afterwards.
Exercise 3: see escaping at work
Pass "<b>bold</b>" as a variable called snippet and print it with and without the safe filter.
Solution. Add "snippet": "<b>bold</b>" to the context, and in the template write {{ snippet }} then {{ snippet|safe }}. The first shows the literal text <b>bold</b>; the second shows bold text. This is why safe is dangerous with user input.
Common mistakes
TemplateDoesNotExist. The file is not atblog/templates/blog/home.html, orblogis not inINSTALLED_APPS.- Using
{{ }}where{% %}is needed. Variables print; tags perform logic. - Forgetting
{% endfor %},{% endif %}or{% endblock %}. - Putting content outside blocks in a child template. It is ignored.
- Using
safeon user input. This opens the door to script injection. - Using a URL name that does not exist. Django raises
NoReverseMatch.
Key takeaways
- Templates separate HTML from Python; views pass data through the context.
{{ }}prints,{% %}runs logic,|applies filters.- Inheritance with
extendsandblockremoves repeated HTML. - Autoescaping protects against XSS; avoid
safeon user data. - Partials (Django 6.0) name small reusable fragments.
Official links
- Templates: https://docs.djangoproject.com/en/6.1/topics/templates/
- Built-in tags and filters: https://docs.djangoproject.com/en/6.1/ref/templates/builtins/
- Template language: https://docs.djangoproject.com/en/6.1/ref/templates/language/
