Explore Flask

8.3. Inheritance

Much like Batman's backstory, a well organized templates directory relies heavily on inheritance. The parent template usually defines a generalized structure that all of the child templates will work within. In our example, layout.html is a parent template and the other .html files are child templates.

You'll generally have one top-level layout.html that defines the general layout for your application and one for each section of your site. If you take a look at the directory above, you'll see that there is a top-level myapp/templates/lay-out.html as well as myapp/templates/profile/layout.html and myapp/templat-es/admin/layout.html. The last two files inherit and modify the first.

Inheritance is implemented with the {% extends %} and {% block %} tags. In the parent template, we can define blocks which will be populated by child templates.

{# _myapp/templates/layout.html_ #}

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>{% block title %}{% endblock %}</title>
    </head>
    <body>
    {% block body %}
        <h1>This heading is defined in the parent.</h1>
    {% endblock %}
    </body>
</html>

In the child template, we can extend the parent template and define the contents of those blocks.

{# _myapp/templates/index.html_ #}

{% extends "layout.html" %}
{% block title %}Hello world!{% endblock %}
{% block body %}
    {{ super() }}
    <h2>This heading is defined in the child.</h2>
{% endblock %}

The super() function lets us include whatever was inside the block in the parent template.

Note For more information on inheritance, refer to the Jinja Template Inheritence documentation.