Modularize Templates – {% include %} tag
In web page design, several design components can be re-utilized on several pages, such as the navigation top bar or footer. Django templates can support the elimination of redundancy by modularizing templates. The {% include %}
tag is used to include the modular parts in a template file.
Practice
Objective:
Learn how to use modular Django templates
In this practice, we'll demonstrate how to modularize template files.
1. Create module templates
We'll create three module templates.
- css_link.html
- navbar.html
- footer.html
For better folder management, create a base directory under the templates directory and place the base.html and the three new HTML files. The directory structure will be like the one below.
2. Adjust other template files to keep the link with base.html
As you moved the base.html file, you need to adjust the path to the file in other template files. Edit each of the following files.
- course_create.html
- course_delete.html
- course_detail.html
- course_list.html
- course_update.html
Add the yellow part of the code to the top of each file.
:
{% block body %}
{% extends "base/base.html" %}
:
3. Move the code to each module template from base.html
Cut out each part of the code and paste it into each template file like shown below.
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/....>
<nav class="navbar navbar-expand-lg bg-body-tertiary">
<div class="container-fluid">
:
</div>
</nav>
<h6 class="text-muted text-center mt-5" style="font-size:0.8rem">2023 Employee Learning</h6>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha2/...."></script>
4. Add {% include %} tags in base.html
Add {% include %}
tags with related HTML paths in the place where you cut the code. The base.html file becomes very simple, as shown below.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Employee Learning</title>
{% include "base/css_link.html" %}
</head>
<body>
{% include "base/navbar.html" %}
{% block body %}
<p>Insert body contents here</p>
{% endblock %}
{% include "base/footer.html" %}
</body>
</html>
Check the browser. As the actual code doesn't change, each page should stay the same.