What is Template Inheritance?

  • Template inheritance is a concept used in web development that allows for a hierarchical organization of the structure and layout of a website, making it easier to manage and maintain. It allows reuse of common page structures across multiple templates. This concept is commonly employed in various templating engines and web development frameworks. In other words, it makes it easier to change the overall look and feel of a project.

The Parent Template:

  • In order to implement template inheritance, we’ll start by creating a template called base.html. Create this file in the same directory as index.html.

VS Code Explorer showing the code_journals templates folder with base.html and index.html listed together

  • This file will contain elements common to all pages and every other template will inherit from base.html. Every page will have a link back to the home page.
  • Because we’ll include this template on every page, let’s make the title a link to the home page:

base.html

base.html code with a home page link using the url template tag and a content block placeholder for child templates

  • This file first creates a paragraph containing the name of the project, which also acts as a link to the home page.
  • The template tag (not to be confused with a simple anchor tag) is used to generate the link, indicated by the braces and percent signs: {% %}.
  • In line 4, a pair of block tags are inserted. This block, named content is a placeholder. The child template will define the kind of information that goes in the content block.

The Child Template:

  • In a child template, we only need to include content that’s unique to that page.
  • A child template must have an {% extends %} on the first line to tell Django which parent template to inherit from.
  • In our project, we need to rewrite index.html to inherit from base.html.
  • Everything contained in the base.html template is pulled in and allows index.html to define what goes in the space reserved by the content block.

index.html

html
1{% extends 'code_journals/base.html' %}
2
3{% block content %}
4    <p>Code Journal tracks your Python knowledge of the topics covered in CIS 240</p>
5{% endblock content %}
  • Note everything that we aren’t inheriting from the parent template goes inside a content block.