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 template is the frame and the pages fill it.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
Medium- In
base.html, put an empty block namedcontentinside<main>. - Make
home.htmlanddrinks.htmlextend"menu/base.html", with their own HTML inside that block.
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