Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 72 ยท Templates with Jinja

Template Inheritance and Includes

Build one layout and reuse it everywhere. Learn Jinja extends, block, super(), include, import and macros in Flask, with runnable in-memory templates.

Almost every page on a website shares the same skeleton: a header, a navigation bar, a footer, the same stylesheet. If you copied that skeleton into every template, a change to the menu would mean editing dozens of files. Jinja solves this with template inheritance. You write the skeleton once in a base template and mark the places where pages may differ with named blocks. Each page template then says "I extend the base" and fills in only its own blocks.

Inheritance is the biggest structural idea in Jinja, and it pairs with two smaller tools: include, which pastes a fragment into a page, and macros with import, which give you reusable, parameterized pieces of HTML. By the end of this lesson you will be able to build a layout with a title, a navigation bar and a content area, and reuse it across a whole site. If you have not met render_template_string and variables yet, start with Jinja template basics and loops and conditionals.

Templates that live in memory

In a real project, templates are files in a templates/ folder next to your app, and render_template("page.html") finds them there. The editors in this tutorial have no real folder, so the examples register templates from a Python dictionary instead. This is a normal Jinja feature: a DictLoader maps template names to source strings.

Python
from jinja2 import DictLoader
app.jinja_loader = DictLoader({"base.html": "...", "page.html": "..."})

After that line, render_template("page.html") works exactly as it would with files, including extends and include. At home you would simply save each string as a file. The dictionary keys play the role of file paths, so "partials/nav.html" is a valid key.

A base template and a child

Here is the smallest useful pair. The base defines two blocks, title and content. The child declares {% extends "base.html" %} as its first tag and fills the blocks.

Python A base layout and two pages

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Read the two outputs side by side. The header and footer are identical, because they come from base.html. The home page replaced title with Home. The about page did not define title, so it kept the base's default text, Untitled. That is how defaults work: whatever you put inside a block in the base is used unless a child overrides it.

flowchart TD
    B["base.html<br/>title block, content block"]
    H["home.html<br/>extends base"]
    A["about.html<br/>extends base"]
    H -->|fills title and content| B
    A -->|fills content only| B
    B --> R["Final HTML sent to the browser"]

A child never stands alone: Jinja loads the base, then swaps in the child's blocks and renders the result.

Rules of extends

A few rules prevent most beginner mistakes:

  • {% extends %} must be the first tag in the child. Anything outside a block in a child template is ignored once it extends something, apart from tags such as set that run before the layout is rendered.
  • Block names must be unique within one template. Two blocks both called content in the same file is an error.
  • You can only override a block that exists in a parent. A block in the child with no matching name in the base is never rendered.
  • A child can itself be a parent. Inheritance chains of any depth work, and the deepest child wins for each block.

Calling the parent with super()

Sometimes you do not want to replace a block, only add to it. Inside a block, {{ super() }} renders the parent's version of that block at that spot. A common use is a styles or scripts block in the head: the base loads the site stylesheet, and a page appends its own.

Python Extending a block with super()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The chain is three levels deep: article.html extends section.html, which extends base.html. Each level calls super(), so the stylesheets accumulate in order: site, then section, then article. Leave out one super() call and the levels above it vanish from that block.

Two other details are worth knowing. You can write {% endblock content %} with the name repeated, which makes long templates easier to read. And {{ self.title() }} renders another block of the current template, useful when the page title should also appear as the <h1>, without repeating the text.

Include: pasting in a fragment

{% include "partials/nav.html" %} renders another template at that point and inserts the result. Use it for chunks that do not need to be overridden: a navigation bar, a footer, a cookie notice. Included templates automatically see the variables of the including template, loops and all.

You can make an include forgiving with {% include "ads.html" ignore missing %}, which renders nothing if the file does not exist, and you can pick the first existing file from a list: {% include ["custom_footer.html", "footer.html"] %}.

Python Includes inside a loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The partial uses the name book, which exists only because the include sits inside the for loop. That is convenient, but it makes the partial depend on its surroundings. If you want a self-contained piece with explicit inputs, a macro is the better tool.

Include or extend? Use extends when a page is a variation of a layout. Use include when a page contains a reusable piece. A page extends one layout but can include as many fragments as it likes.

Macros and import

A macro is a template function. It takes arguments, may have defaults, and returns HTML. Because the arguments are explicit, a macro is easier to reuse and test than an include. Put your macros in a file such as macros.html and bring them in with import.

Python A macro library imported into a page

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Notice what happened to the quotes in the title: the output contains &#34;, not a raw ". Flask turns on autoescaping for templates ending in .html, so values passed into a macro are escaped when printed. The macro's own HTML is trusted, because it is template source, not data.

There are two import styles:

JINJA
{% from "macros.html" import badge, field %}
{% import "macros.html" as ui %}
{{ ui.badge("New") }}

By default, an imported template does not receive the current request's variables, which keeps macros predictable. If a macro file really needs the context, write {% import "macros.html" as ui with context %}.

A realistic layout with a navigation partial

Let us combine everything. The base layout includes a navigation partial; the partial marks the current page by comparing request.path. In templates, Flask gives you request, session, g and url_for without passing them. See building URLs with url_for for why you should generate links instead of typing them.

Python Layout, partials and an active menu item

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

On / only the Home link carries class="active"; on /books only Books does. The <h1> was produced with self.title(), so each page states its title once. This layout-plus-partials pattern is the backbone of most Flask sites. When your app grows into blueprints, each blueprint can have its own templates folder and still extend the shared layout.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which tag must come first in a child template?

    A child declares its parent with extends before anything else. Without it, the template is just a stand-alone page.
  2. 2. A child template does not define the block that the base template defines. What is rendered for that block?

    Blocks in the base act as defaults. A child only replaces the blocks it names.
  3. 3. What does super() do inside a block?

    super() lets a child add to a block instead of replacing it, for example to append another stylesheet.
  4. 4. When should you prefer a macro over an include?

    A macro is like a function with parameters and defaults, so its inputs are explicit. An include silently reads the surrounding variables.
  5. 5. By default, does a template loaded with {% import "macros.html" as ui %} see the current request's variables?

    Imports are cached and rendered without the context by default. Add 'with context' only when a macro really needs it.

Summary

  • A base template defines {% block name %} areas; a child starts with {% extends "base.html" %} and overrides the blocks it needs.
  • Block contents in the base are defaults, and inheritance chains can be any depth.
  • {{ super() }} renders the parent's block; {{ self.name() }} renders another block of the current template.
  • {% include %} pastes a fragment that can see the current variables; ignore missing and lists of names make it forgiving.
  • Macros are template functions; bring them in with {% from ... import ... %} or {% import ... as ... %}.
  • In examples, app.jinja_loader = DictLoader({...}) stands in for a templates/ folder.

Next up: shape your data for display with filters, tests and custom helpers.