Django 3 : Extending the templates

The legacy of templates allows you to define a super template and a subtemplate that inherits from the super template. In the super template, it is possible to define blocks that subtemplates can fill.

We will use an example where the page.html template will extend the base.html template.

Step 1 : The following is the base.html template code, which we must create in the template folder:

Step 2 : In the previous code, we defined three areas that the child templates can override: title, h1, and content. The following is the page.html template code:

If you need to get the content of the block from the parent template, the {{ block.super }} variable will do the trick. This is useful if you want to add to the contents of a parent block instead of completely overriding it.

Step 3 : We will create a second page in our application. Add the following line to the urls.py file:

Step 4 : Then, create a view. Add the following line to the views.py file:

Step 5 : Typing the http://localhost:8000/page URL in our browser.