In this Django Tutorial we are going to talk about Django Template Inheritance, so it is the most powerful and complex part of Django template engine, so using Django Template Inheritance we can create a base skeleton template that contains all common elements of our site and define blocks that child templates can override.
OK as we have already created our index.html file in the previous lesson, right now we have just one html file, now when you are going to develop a web application, maybe you have more than ten html files, so on that time it is good to use django template inheritance.
Now create another html file and you need to call that base.html, this is the html file that we are going to create our blocks, and after that our child templates can extends this base.html and can override the block contents.
templates/base.html
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> </head> <body> {% block body %} {% endblock %} </body> </html> |
In this example, the block
tag defines two blocks that child templates can fill in. All the block
tag does is to tell the template engine that a child template may override those portions of the template.
A child template might look like this – templates/index.html.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
{% extends 'base.html' %} {% block title %} Home {% endblock %} {% block body %} <h1>Welcome to {{name}}</h1> <p>Tutorial Number 7 - Django Template Inheritance</p> {{pro_list}} {% endblock %} |
The extends
tag is the key here. It tells the template engine that this template “extends” another template. When the template system evaluates this template, first it locates the parent – in this case, “base.html”.
At that point, the template engine will notice the twoblock
tags in base.html
and replace those blocks with the contents of the child template.
Now if you run your project we have the same result.