BudiBadu Logo
Samplebadu

Flask by Example: Template Inheritance System

Flask 3.0+

Template inheritance allows you to build a base "skeleton" template that contains all the common elements of your site and defines blocks that child templates can override.

Code

<!-- base.html -->
<!DOCTYPE html>
<html>
<head>
    {% block head %}
    <title>{% block title %}{% endblock %} - My App</title>
    {% endblock %}
</head>
<body>
    <nav>
        <a href="/">Home</a>
    </nav>
    
    <div id="content">
        {% block content %}{% endblock %}
    </div>
    
    <footer>
        {% block footer %}
        &copy; 2023 My App
        {% endblock %}
    </footer>
</body>
</html>

<!-- child.html -->
{% extends "base.html" %}

{% block title %}Index{% endblock %}

{% block head %}
    {{ super() }}
    <style type="text/css">
        .important { color: #336699; }
    </style>
{% endblock %}

{% block content %}
    <h1>Index</h1>
    <p class="important">
        Welcome to my awesome homepage.
    </p>
{% endblock %}

Explanation

Jinja2's template inheritance allows you to define a base template that contains the common HTML skeleton of your site. This base template defines blocks that child templates can override to inject their specific content.

Child templates use the {% extends "base.html" %} tag to indicate inheritance. This system eliminates code duplication, as you only need to define your navigation, footer, and imports in one place.

The {{ super() }} function is a powerful feature that allows you to add to the parent block's content rather than replacing it entirely. This is commonly used for appending page-specific CSS files or scripts to the head block defined in the base template.

Code Breakdown

5
{% block head %} defines a block named "head". Child templates can inject extra meta tags or styles here.
27
{% extends "base.html" %} must be the very first tag in the child template. It establishes the inheritance link.
32
{{ super() }} renders the content of the parent block. Here, it ensures that the <title> tag defined in the parent's head block is preserved, while adding the custom style tag after it.
37
{% block content %} overrides the empty content block from the base template, injecting the page-specific HTML.