Skip to main content

Extending Templates

You will much likely have repeated code between the different templates of your application. For example, the header and footer of a website usually appear on all pages. To avoid having the same blocks of code on each page, Django provides a template inheritance feature.

Let's create, for example, a base template named templates/myapp/layout.html:

<!doctype html>
<html>
<head>
<title>
{% block title %}
My Django application
{% endblock %}
</title>
</head>
<body>
<main>
{% block content %}
{% endblock %}
</main>
<footer>
<small>&copy; My Django Application</small>
</footer>
</body>
</html>

We are defining an HTML document with a title, a main section and a footer. Note that we defined two blocks using Django's {% block ... %} tag. This will allow you to replace those blocks from templates that extend this layout document. Now, in templates/myapp/index.html:

<!-- Indicate that we want to extend the layout.html file. -->
{% extends "myapp/layout.html" %}

<!-- This block will replace the original title "My Django Application". -->
{% block title %}
List of students
{% endblock %}

<!-- This block will be placed inside the <main> tag of layout.html. -->
{% block content %}
<h1>List of students</h1>
<ul>
{% for student in students %}
<li>{{ student }}</li>
{% endfor %}
</ul>
{% endblock %}