Menu
CoddyTech

Template Inheritance

Part of the Django Basics section of Coddy's Django journey. Lesson 17 of 23.

home.html and drinks.html each repeat the same <head>, and soon a nav bar too. Change the frame and you edit every file. Instead, one base template is the frame around every page, and each page fills in its own part. Django calls the frame the parent template and each page a child.

The frame marks the part a page fills with a {% block %} tag and a name. A library's library/base.html:

<body>
    <nav>...</nav>
    <article>{% block body %}{% endblock %}</article>
</body>

A page starts with {% extends %}, then fills the block:

{% extends "library/base.html" %}

{% block body %}
    <p>We are open until 20:00.</p>
{% endblock %}

{% extends %} must be the first tag. In a page that extends another, anything outside a block is dropped: a heading you forget to wrap vanishes.

challenge icon

Challenge

Medium

Make both pages share the frame in base.html.

  1. In base.html, put an empty block named content inside <main>.
  2. In home.html, extend "menu/base.html" on the first line. Keep only what was inside <body>, and put it in the content block.
  3. Do the same in drinks.html.

Press Run: both pages show the nav from base.html.

Try it yourself

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Corner Café</title>
</head>
<body>
    <nav>
        <a href="{% url 'menu:home' %}">Home</a>
        <a href="{% url 'menu:drinks' %}">Drinks</a>
        <a href="{% url 'menu:about' %}">About</a>
    </nav>
    <main>
        <!-- each page's content goes here -->
    </main>
</body>
</html>

All lessons in Django Basics

Practice on your own: Django playground