Solution details

Django templates have a powerful extension mechanism. Similar to classes in programming, a template can be extended through inheritance. However, for that to work, the base itself must be structured into blocks as follows:

Modular base templates can be extended by individual page templates giving flexibility and consistent layout

The base.html template is, by convention, the base structure for the entire site. This template will usually be well-formed HTML (that is, with a preamble and matching closing tags) that has several placeholders marked with the {% block tags %} tag. For example, a minimal base.html file looks as follows:

<html> 
<body> 
<h1>{% block heading %}Untitled{% endblock %}</h1> 
{% block content %} 
{% endblock %} 
</body> 
</html> 

There are two blocks here, heading and content, which can be overridden. You can extend the base to create specific pages that can override these blocks. For example, here is an About page:

{% extends "base.html" %} 
{% block content %} 
<p> This is a simple About page </p> 
{% endblock %} 
{% block heading %}About{% endblock %} 
We do not have to repeat the entire structure. We can also mention the blocks in any order. The rendered result will have the right blocks in the right places as defined in base.html.

If the inheriting template does not override a block, then its parent's contents are used. In the preceding example, if the About template does not have a heading, then it will have the default heading of Untitled. You can insert the parent's contents explicitly using {{ block.super }}, which can be useful when you want to append or prepend to it.

The inheriting template can be further inherited forming an inheritance chain. This pattern can be used as a common derived base for pages with a certain layout, for example, a single-column layout. A common base template can also be created for a section of the site, for example, Blog pages.

Usually, all inheritance chains can be traced back to a common root, base.html; hence, the pattern's name: Template inheritance tree. Of course, this need not be strictly followed. The error pages 404.html and 500.html are usually not inherited and are stripped bare of most template tags to prevent further errors.

Another way of achieving this might be to use context processors. You can create a context processor, which will add a context variable that can be used in all your templates globally. But this is not advisable for common markup such as sidebars as it violates the separation of concerns by moving presentation out of the template layer.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.210.17