Skip to content
Myr

templateinheritance.rst

This file

Path

docs/patterns/templateinheritance.rst

68 lines · 2.1 KiB

Last changed by

Not known.

History of this file

Take it

The walk stopped after 200 commits: lines older than 73739a2 point at it.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 1–68why, one step back
1Template Inheritance
2====================34The most powerful part of Jinja is template inheritance. Template inheritance5allows you to build a base "skeleton" template that contains all the common6elements of your site and defines **blocks** that child templates can override.78Sounds complicated but is very basic. It's easiest to understand it by starting9with an example.101112Base Template13-------------1415This template, which we'll call :file:`layout.html`, defines a simple HTML skeleton16document that you might use for a simple two-column page. It's the job of17"child" templates to fill the empty blocks with content:1819.. sourcecode:: html+jinja2021 <!doctype html>22 <html>23 <head>24 {% block head %}25 <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">26 <title>{% block title %}{% endblock %} - My Webpage</title>27 {% endblock %}28 </head>29 <body>30 <div id="content">{% block content %}{% endblock %}</div>31 <div id="footer">32 {% block footer %}33 &copy; Copyright 2010 by <a href="http://domain.invalid/">you</a>.34 {% endblock %}35 </div>36 </body>37 </html>3839In this example, the ``{% block %}`` tags define four blocks that child templates40can fill in. All the `block` tag does is tell the template engine that a41child template may override those portions of the template.4243Child Template44--------------4546A child template might look like this:4748.. sourcecode:: html+jinja4950 {% extends "layout.html" %}51 {% block title %}Index{% endblock %}52 {% block head %}53 {{ super() }}54 <style type="text/css">55 .important { color: #336699; }56 </style>57 {% endblock %}58 {% block content %}59 <h1>Index</h1>60 <p class="important">61 Welcome on my awesome homepage.62 {% endblock %}6364The ``{% extends %}`` tag is the key here. It tells the template engine that65this template "extends" another template. When the template system evaluates66this template, first it locates the parent. The extends tag must be the67first tag in the template. To render the contents of a block defined in68the parent template, use ``{{ super() }}``.