Django is a high-level web framework written in Python. Being a web framework, Django must be able to run HTML files as the main component of the web. Django uses the template engine to do this. Inheritance is parts of the Django template engine that can be used to run dynamic HTML by rendering files.
A template contains the static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. Special syntax called the Django Template Language (DTL) used to run dynamic content into a static HTML template.
The most powerful and thus the most complex part of Django’s template engine is template inheritance. Template inheritance allows you to build a base skeleton template that contains all the common elements of your site and defines blocks that child templates can override. Let’s look at the template inheritance example.
I create a parent template looks like this:
This template, which I’ll call blue-print.html will be the parent template, defines an HTML skeleton document that you might use for two content (id=”content1”, id=”content2”) in page HTML. It’s the job of “child” templates to fill the empty blocks (lines 12 and 18) or inside block content1 and block content2 with content.
I create a child template home.html looks like this:
This template, which I’ll call home.html will be the child template. The extends tag (line 1) is the key here. It tells the template engine that this template “extends” another template. When the template system evaluates this child template, first it locates the parent, in this case, blue-print.html.
At that point, the template engine will notice the two empty block tags in parent template blue-print.html (lines 12 and 18) and replace those blocks with the contents of the child template. The output child template home.html might look like:
It can be seen that the child template home.html generates skeleton HTML documents (there is tag <html>, <head>, <body>, etc.) even though in the child template home.html I don’t write those tags, this is because the child template extends to the parent template and inherits all elements in the parent template.
This also applies to other child templates, for example, I create a new child template which I’ll call about.html looks like this:
The output a new child template about.html might look like:
That’s good, from the example it can be concluded that the parent template can be reused in child template, note: that the child template must “extends” the parent template (“line 1”). So, elements that are not in the child template will be automatically inherited by the parent template. This is very useful if we create multiple pages with the same template but with different content. By using template inheritance we no longer need to write an HTML skeleton document for further files.
Let’s try with the Django Template Language inheritance by creating a new child template contact.html. Good luck!