🎓 A1Learner
🔍
0 of 50 lessons completed

Django Template Inheritance

Template inheritance lets many pages share one layout. A child template fills the holes of a parent.

The parent layout

The parent holds the heading and one empty block. The file is named base.html.

<h1>My Site</h1>
{% block body %}{% endblock %}

The child page

The child names the parent first. Then it fills the body block.

{% extends "base.html" %}
{% block body %}<p>Hello page</p>{% endblock %}

Render the child

The view renders the child file by name. Django loads the parent behind it.

def page(request):
    return render(request, "child.html")

Ask for the page

The test client loads the page and shows the joined page, parent layout plus child block.

from django.test import Client

client = Client()
print(client.get("/page/").content.decode())

Example

import django
from django.conf import settings

settings.configure(
    DEBUG=True,
    SECRET_KEY="key",
    ROOT_URLCONF=__name__,
    ALLOWED_HOSTS=["*"],
    TEMPLATES=[{"BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ["templates"], "APP_DIRS": True}],
)
django.setup()

import os

os.makedirs("templates", exist_ok=True)
with open("templates/base.html", "w") as f:
    f.write("<h1>My Site</h1>\n{% block body %}{% endblock %}")
with open("templates/child.html", "w") as f:
    f.write('{% extends "base.html" %}\n{% block body %}<p>Hello page</p>{% endblock %}')

from django.shortcuts import render
from django.urls import path

def page(request):
    return render(request, "child.html")

urlpatterns = [path("page/", page)]

from django.test import Client

client = Client()
print(client.get("/page/").content.decode())

Key points

  • The parent holds the shared HTML and its {% block %} marks.
  • A block is a named hole that the child fills.
  • The child points at the parent with {% extends %}.
  • The child fills each block with page HTML of its own.
  • One layout covers every page of the site.

In this example, the setup lines configure Django with a templates folder. The program writes the parent and child files into that folder first. The parent keeps the heading and the body block. A child takes the parent layout and fills its block. The view builds the page from the child, and the test client displays the joined page.

Note

Block names must agree between parent and child.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What job does {% extends "base.html" %} do for a child template?