Labs ICT
โญ Pro Login

Template Inheritance

Building reusable page layouts with extends.

Why Template Inheritance?

Imagine you have 50 pages on your website. Each page has the same header, footer, and navigation bar. Without inheritance, you'd copy those elements into every single template. That's a maintenance nightmare โ€” change the footer once and you'd have to update 50 files.

Template inheritance solves this by letting you define common elements in a base template and override only what changes in child templates.

Creating a Base Template

A base template defines the overall structure of your pages using {% block %} tags. These blocks mark sections that child templates can override.


<!DOCTYPE html>
<html>
<head>
    <title>{% block title %}My Site{% endblock %}</title>
    {% block extra_css %}{% endblock %}
</head>
<body>
    <header>
        <nav>...</nav>
    </header>

    <main>
        {% block content %}
            Default content if child doesn't override.
        {% endblock %}
    </main>

    <footer>...</footer>
    {% block extra_js %}{% endblock %}
</body>
</html>
    

Blocks can have default content. If a child template doesn't override a block, the base template's content is used.

Extending the Base Template

Child templates use {% extends %} to inherit from the base. They only need to define the blocks they want to override.


{% extends "base.html" %}

{% block title %}{{ page_title }} | My Site{% endblock %}

{% block content %}
    <h1>{{ page_title }}</h1>
    <p>{{ body_text }}</p>
{% endblock %}
    

The {% extends %} tag must be the very first template tag. Everything outside of blocks is ignored.

Try it Yourself โ†’

Using block.super()

Sometimes you want to add to a block's content instead of replacing it entirely. Use {{ block.super }} to include the parent template's block content.


{% extends "base.html" %}

{% block extra_css %}
    {{ block.super }}
    <link rel="stylesheet" href="page-specific.css">
{% endblock %}

{% block content %}
    <div class="page-wrapper">
        {{ block.super }}
    </div>
{% endblock %}
    

This is useful when you want to add CSS, JavaScript, or wrapper elements around the parent's content without losing it.

Component Patterns

Combine {% extends %} and {% include %} to build reusable components. Use inheritance for page structure and includes for shared UI elements.


{% extends "base.html" %}

{% block content %}
    {% include "components/alert.html" with message="Welcome!" %}

    <div class="sidebar">
        {% include "components/sidebar.html" %}
    </div>

    <div class="main">
        {% block main_content %}{% endblock %}
    </div>
{% endblock %}
    

This pattern keeps your templates modular and maintainable. Each component handles its own logic, and the page templates stay clean and focused.

๐Ÿงช Quick Quiz

What does the {% extends %} template tag do?