Django 3 : Extending the templates

Louis SanchezFebruary 27th 2021, 11:27

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:


          {% block title %}{% endblock %}
          {% block h1 %}Tasks Manager : {% endblock %}
          {% block content %}{% endblock %}

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:

{% extends "base.html" %}
{% block title %}
  Hello World Title
{% endblock %}
{% block h1 %}
  {{ block.super }}Hello World Django
{% endblock %}
{% block content %}
  Hello world !
{% endblock %}

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 file:


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

def page(request):
  return render(request, 'page.html')

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