Django 3 : Extending the templates

Louis SanchezNovember 26th 2020, 8:38

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:

<html>

  <head>
      <title>
          {% block title %}{% endblock %}
      </title>
  </head>
  
  <body>
      <h1>
          {% block h1 %}Tasks Manager : {% endblock %}
      </h1>
      <div>
          {% block content %}{% endblock %}
      </div>
  </body>
  
  </html>

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 urls.py file:

path('page', views.page),

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

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

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