The template inheritance feature allows you to create a base template with common content and structure, and then inherit from it in child templates to add specific content or variations. One significant advantage of using template inheritance is that it enables you to establish a consistent layout across multiple templates: this can save you a lot of time and effort, as the base template only needs to be defined once and can then be reused at will.
Let's see an example of base template (saved as base.html
):
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}Default Title{% endblock %}</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<main>
{% block content %}{% endblock %}
</main>
</body>
</html>
The block/endblock
sections in the above template declare named parts of the template that children templates can overwrite: these blocks may be empty or provide a default value. All blocks need to have a unique name.
Let's see an example of child template:
{% extends "base.html" %}
{% block title %}Contact Us{% endblock %}
{% block content %}
Contact Us
Get in touch with us for any inquiries, suggestions, or feedback.
{% endblock %}
The first line of any child template must declare which base template it extends using the extends
keyword.
This child template then provides content for both the title
and content
blocks: rendering it will result in the following HTML document:
<!DOCTYPE html>
<html>
<head>
<title>Contact Us</title>
</head>
<body>
<header>
<h1>My Website</h1>
</header>
<main>
<h2>Contact Us</h2>
<p>Get in touch with us for any inquiries, suggestions, or feedback.</p>
</main>
</body>
</html>
Multiple children can inherit from the same base template: for example, you could also create an About
page.
Sign up and start using PushMetrics for free.
Or schedule a demo and discuss your use case.