Template Inheritance

The most powerful part of Jinja is template inheritance. Template inheritanceallows you to build a base “skeleton” template that contains all the commonelements of your site and defines blocks that child templates can override.

Sounds complicated but is very basic. It’s easiest to understand it by startingwith an example.

Base Template

This template, which we’ll call layout.html, defines a simple HTML skeletondocument that you might use for a simple two-column page. It’s the job of“child” templates to fill the empty blocks with content:

  1. <!doctype html>
  2. <html>
  3. <head>
  4. {% block head %}
  5. <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
  6. <title>{% block title %}{% endblock %} - My Webpage</title>
  7. {% endblock %}
  8. </head>
  9. <body>
  10. <div id="content">{% block content %}{% endblock %}</div>
  11. <div id="footer">
  12. {% block footer %}
  13. &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.
  14. {% endblock %}
  15. </div>
  16. </body>
  17. </html>

In this example, the {% block %} tags define four blocks that child templatescan fill in. All the block tag does is tell the template engine that achild template may override those portions of the template.

Child Template

A child template might look like this:

  1. {% extends "layout.html" %}
  2. {% block title %}Index{% endblock %}
  3. {% block head %}
  4. {{ super() }}
  5. <style type="text/css">
  6. .important { color: #336699; }
  7. </style>
  8. {% endblock %}
  9. {% block content %}
  10. <h1>Index</h1>
  11. <p class="important">
  12. Welcome on my awesome homepage.
  13. {% endblock %}

The {% extends %} tag is the key here. It tells the template engine thatthis template “extends” another template. When the template system evaluatesthis template, first it locates the parent. The extends tag must be thefirst tag in the template. To render the contents of a block defined inthe parent template, use {{ super() }}.