templateinheritance.rst
This file
Path
docs/patterns/templateinheritance.rst
69 lines · 2.1 KiB
Last changed by
Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption79aa4ac
History of this fileTake it
The walk stopped after 200 commits: lines older than de3b6ab point at it.
Fixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 1–40why, 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-------------1617This template, which we'll call ``layout.html``, defines a simple HTML skeleton18document 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>3940In this example, the ``{% block %}`` tags define four blocks that child templatesMerge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption79aa4ac
line 41why, one step back41can fill in. All the `block` tag does is tell the template engine that aFixed a broken sentence about blueprints.Armin Ronacherbefore adoptionde3b6ab
lines 42–69why, one step back42child template may override those portions of the template.4344Child Template45--------------4647A child template might look like this:4849.. sourcecode:: html+jinja5051 {% extends "layout.html" %}52 {% block title %}Index{% endblock %}53 {% block head %}54 {{ super() }}55 <style type="text/css">56 .important { color: #336699; }57 </style>58 {% endblock %}59 {% block content %}60 <h1>Index</h1>61 <p class="important">62 Welcome on my awesome homepage.63 {% endblock %}6465The ``{% extends %}`` tag is the key here. It tells the template engine that66this template "extends" another template. When the template system evaluates67this template, first it locates the parent. The extends tag must be the68first tag in the template. To render the contents of a block defined in69the parent template, use ``{{ super() }}``.