Extend Templates – {% extends %} tag
In the web page design, there are several pages using a similar design structure. Django templates can support the creation of a master template. Then, each page can customize the master template by extending the master template. The {% extends %}
tag is used to extend the master template.
Here are the key steps to make extended templates.
- Create parent.html (or base.html)
- In the parent file, add code for commonly used sections
- In the parent file, add
{% block name %}
and{% endblock %}
for the section that you want to customize - Create
child.html
- In the child file, add
{% extends "parent.html" %}
in the beginning of the file - In the child file, add code between
{% block name %}
and{% endblock %}
By implementing this, when the child.html template is rendered, parent.html and child.html are integrated and displayed in the browser as one HTML document.
Practice
Objective:
Learn how to use template extension
In this practice, we'll demonstrate a template extension.
1. Create base.html directly under templates directory
Assuming the base template is used by several applications in the project, we create the base.html file directly under the templates directory.
2. Edit the base.html file
Open the base.html file and edit the following three points.
- The first two lines are links to the list page and create page.
- The
{% block body %}
...{% endblock %}
part will be overwritten by the other HTML files. - The last part is a footer.
<a href="{% url 'course_list'%}">List</a>
<a href="{% url 'course_create'%}">Create</a>
{% block body %}
<p>Insert body contents here</p>
{% endblock %}
<h6>2023 Employee Learning</h6>
3. Edit other template files
Open the template file and do the following:
- Add the
{% extends "base.html" %}
tag in the begining - Delete the links to the list page and the create page that are already written in the base.html file.
- Add the
{% block body %}
and{% endblock %}
tags
The code below is an example of the create page template. The yellow lines are the new code.
{% extends "base.html" %}
{% block body %}
<h1> CREATE Page </h1>
:
</form>
{% endblock %}
4. Check the results in a browser
After repeating the same thing for all the files, access to localhost:8000/employee-learning/course-list/. You can see that the pages still display the same content, although you have changed the template structure.