templateinheritance.rst
This file
Path
docs/patterns/templateinheritance.rst
70 lines · 2.2 KiB
Last changed by
Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
History of this fileTake it
The walk stopped after 200 commits: lines older than 36d70d8 point at it.
Merge pull request #843 from wbowlin/masterDaniel Neuhäuserbefore adoption36d70d8
lines 1–16why, one step back1.. _template-inheritance:23Template Inheritance4====================56The most powerful part of Jinja is template inheritance. Template inheritance7allows you to build a base "skeleton" template that contains all the common8elements of your site and defines **blocks** that child templates can override.910Sounds complicated but is very basic. It's easiest to understand it by starting11with an example.121314Base Template15-------------16Merge pull request #1240 from defuz/docs-style-fix-2Markus Unterwaditzerbefore adoption6fcc2ae
line 17why, one step back17This template, which we'll call :file:`layout.html`, defines a simple HTML skeletonMerge pull request #843 from wbowlin/masterDaniel Neuhäuserbefore adoption36d70d8
lines 18–70why, one step back18document that you might use for a simple two-column page. It's the job of19"child" templates to fill the empty blocks with content:2021.. sourcecode:: html+jinja2223 <!doctype html>24 <html>25 <head>26 {% block head %}27 <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">28 <title>{% block title %}{% endblock %} - My Webpage</title>29 {% endblock %}30 </head>31 <body>32 <div id="content">{% block content %}{% endblock %}</div>33 <div id="footer">34 {% block footer %}35 © Copyright 2010 by <a href="http://domain.invalid/">you</a>.36 {% endblock %}37 </div>38 </body>39 </html>4041In this example, the ``{% block %}`` tags define four blocks that child templates42can fill in. All the `block` tag does is tell the template engine that a43child template may override those portions of the template.4445Child Template46--------------4748A child template might look like this:4950.. sourcecode:: html+jinja5152 {% extends "layout.html" %}53 {% block title %}Index{% endblock %}54 {% block head %}55 {{ super() }}56 <style type="text/css">57 .important { color: #336699; }58 </style>59 {% endblock %}60 {% block content %}61 <h1>Index</h1>62 <p class="important">63 Welcome on my awesome homepage.64 {% endblock %}6566The ``{% extends %}`` tag is the key here. It tells the template engine that67this template "extends" another template. When the template system evaluates68this template, first it locates the parent. The extends tag must be the69first tag in the template. To render the contents of a block defined in70the parent template, use ``{{ super() }}``.