SyntaxStudy
Sign Up
Django Template Inheritance with extends and block
Django Beginner 1 min read

Template Inheritance with extends and block

Template inheritance is one of Django's most powerful template features. A base template defines the overall page structure — HTML skeleton, navigation, footer, and named {% block %} placeholders. Child templates use {% extends "base.html" %} to inherit the base layout and then fill in only the blocks they need to customise. Any block not overridden in the child template retains the content from the base template. The {% block %} tag accepts a name and optionally a default content between opening and closing tags. In a child template you can call {{ block.super }} inside a block to include the parent block's content and then append or prepend to it. This is useful for extending a base CSS block with page-specific styles rather than completely replacing it. The {% include %} tag renders a separate template file and inserts it inline. This is ideal for reusable fragments like a navigation bar, comment form, or social sharing buttons. Unlike {% extends %} (which applies to the whole template), {% include %} can be used anywhere in a template and can pass extra context variables using the with keyword: {% include "partials/card.html" with item=post %}.
Example
{# templates/base.html — the parent layout #}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}My Blog{% endblock %}</title>
    {% block extra_css %}{% endblock %}
</head>
<body>
    <header>
        <nav>
            <a href="{% url 'post-list' %}">Home</a>
            {% if user.is_authenticated %}
                <a href="{% url 'post-create' %}">New Post</a>
                <a href="{% url 'logout' %}">Logout</a>
            {% else %}
                <a href="{% url 'login' %}">Login</a>
            {% endif %}
        </nav>
    </header>

    <main>
        {% if messages %}
            {% for message in messages %}
                <div class="alert alert-{{ message.tags }}">{{ message }}</div>
            {% endfor %}
        {% endif %}

        {% block content %}{% endblock %}
    </main>

    <footer><p>&copy; 2024 My Blog</p></footer>
    {% block extra_js %}{% endblock %}
</body>
</html>

{# templates/blog/post_detail.html — child template #}
{% extends "base.html" %}

{% block title %}{{ post.title }} | My Blog{% endblock %}

{% block content %}
<article>
    <h1>{{ post.title }}</h1>
    <p>{{ post.published_at|date:"F j, Y" }}</p>
    <div class="body">{{ post.body|linebreaks }}</div>
</article>
{% include "blog/partials/comment_form.html" with form=form post=post %}
{% endblock %}