1. The Scenario
In a project, elements such as the header and footer are often reused. To avoid rewriting these elements on every page, and so that a change does not require editing each page individually, the common parts need to be extracted — that is Django template inheritance.
2. Django’s Reusable Template Tags
Django’s built-in reusable template tags are mainly block, extends, and include.
First let us look at an example:
Define a project-wide common template base.html
| |
Using the common base.html template, define the home page index.html
| |
2.1 block
Definition:
block defines a template block. The block in a child template overrides the block of the same name in the parent template. If you want the child template to add to the parent’s content rather than override it, you can use block.super.
Usage:
| |
| |
2.2 extends
Definition:
extends means inheritance. Typically a project writes one base.html and a number of widget.html files. Most pages in the project inherit from base.html.
Usage:
The argument to extends is usually a string, and can also be a variable. Note that when using extends, extends must be the very first tag, otherwise it will not take effect.
| |
Definition:
include adds another template directly into the current template in the manner of a plugin.
Usage:
It may take a path, a relative path, or a variable name.
| |
2.3 Other Template Tags
- autoescape controls the automatic escaping of the template.
| |
- load loads a tag library.
| |
You can also write custom tags. For example, after adding ‘django.contrib.humanize’ to INSTALLED_APPS, you can use load humanize in a template. Note that a loaded tag is not inherited by child templates.
3. Mako
Mako is a high-performance Python template library whose syntax borrows heavily from other template libraries such as Django and Jinja2. At the same time, Mako does not depend on any other Web framework and can be used directly for HTML generation. On first compilation, Mako compiles the HTML template into a Python file, greatly improving the speed of rendering and generating pages.
Mako
- <%include>
Takes a filename as its argument and includes a file.
- <%def>
Defines a Python function:
| |
- <%inherit>
Used for template inheritance.
| |
- <%call>
Used to call a Python function defined by <%def>.
- parent
The namespace of the parent template in the inheritance chain. parent.head() references the parent template’s content from within the index.html child template.
- next
The namespace of the next template in the inheritance chain. The position of next.body() determines where the child page’s content that is not inside a block is rendered. You can also use self.body(), but self.body() only renders content that is not inside a block in the final page, not content that is not inside a block in intermediate pages of the inheritance chain.
| |
