Book Image

Learning Website Development with Django

Book Image

Learning Website Development with Django

Overview of this book

Table of Contents (18 chapters)
Learning Website Development with Django
Credits
About the Author
About the Reviewers
Preface
Index

Improving Template Structure


We have created three templates so far. They all share the same general structure, and only differ in the title and main content. Wouldn't it be great if we could factor out the shared sections into a single file so that, if we want to modify all the pages in future, we need only edit one file?

Fortunately, the Django template system already provides such a feature-template inheritance. The idea is simple; we create a base template that contains the structure shared by all templates in the system. We also declare certain blocks of the base template to be modifiable by child templates. Next, we create a template that extends the base template and modifies its blocks. The idea is very similar to class inheritance in object-oriented programming.

Let's apply this feature to our project. Create a file called base.html in templates with the following content:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional...