Background Image
Table of Contents Table of Contents
Previous Page  148 / 478 Next Page
Information
Show Menu
Previous Page 148 / 478 Next Page
Page Background

yourself ” rule, and bring all the common parts together. Thankfully, the Django tem‐

plate language makes that easy using something called template inheritance.

Django Template Inheritance

Let’s have a little review of what the differences are between

home.html

and

list.html

:

$

diff lists/templates/home.html lists/templates/list.html

7,8c7,8

< <h1>Start a new To-Do list</h1>

< <form method="POST" action="/lists/new">

---

> <h1>Your To-Do list</h1>

> <form method="POST" action="/lists/{{ list.id }}/add_item">

11a12,18

>

> <table id="id_list_table">

> {% for item in list.item_set.all %}

> <tr><td>{{ forloop.counter }}: {{ item.text }}</td></tr>

> {% endfor %}

> </table>

>

They have different header texts, and their forms use different URLs. On top of that,

list.html

has the additional

<table>

element.

Now that we’re clear onwhat’s in common andwhat’s not, we canmake the two templates

inherit froma common “superclass” template.We’ll start bymaking a copy of

home.html

:

$

cp lists/templates/home.html lists/templates/base.html

We make this into a base template which just contains the common boilerplate, and

mark out the “blocks”, places where child templates can customise it:

lists/templates/base.html.

<html>

<head>

<title>

To-Do lists

</title>

</head>

<body>

<h1>

{% block header_text %}{% endblock %}

</h1>

<form

method=

"POST"

action=

"{% block form_action %}{% endblock %}"

>

<input

name=

"item_text"

id=

"id_new_item"

placeholder=

"Enter a to-do item"

/>

{% csrf_token %}

</form>

{% block table %}

{% endblock %}

</body>

</html>

The base template defines a series of areas called “blocks”, which will be places that other

templates can hook in and add their own content. Let’s see how that works in practice,

by changing

home.html

so that it “inherits from”

base.html

:

120

|

Chapter 7: Prettification: Layout and Styling, and What to Test About It