Skip to content
Myr

templating.rst

This file

Path

docs/templating.rst

261 lines · 8.7 KiB

Last changed by

Merge branch 'stable'David Lordbefore adoption3a9d54f

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–3why, one step back
1Templates
2=========3

Merge branch 'stable'David Lordbefore adoption3301232

lines 4–5why, one step back
4Flask leverages Jinja as its template engine. You are obviously free to use
5a different template engine, but you still have to install Jinja to run

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 6why, one step back
6Flask itself. This requirement is necessary to enable rich extensions.

Merge branch 'stable'David Lordbefore adoption3301232

line 7why, one step back
7An extension can depend on Jinja being present.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 8why, one step back
8

Merge branch 'stable'David Lordbefore adoption3301232

line 9why, one step back
9This section only gives a very quick introduction into how Jinja

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 10why, one step back
10is integrated into Flask. If you want information on the template

Merge branch 'stable'David Lordbefore adoption3301232

line 11why, one step back
11engine's syntax itself, head over to the official `Jinja Template

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 12–17why, one step back
12Documentation <https://jinja.palletsprojects.com/templates/>`_ for
13more information.1415Jinja Setup16-----------17

Merge branch 'stable'David Lordbefore adoption3301232

line 18why, one step back
18Unless customized, Jinja is configured by Flask as follows:

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 19–27why, one step back
19
20- autoescaping is enabled for all templates ending in ``.html``,21 ``.htm``, ``.xml``, ``.xhtml``, as well as ``.svg`` when using22 :func:`~flask.templating.render_template`.23- autoescaping is enabled for all strings when using24 :func:`~flask.templating.render_template_string`.25- a template has the ability to opt in/out autoescaping with the26 ``{% autoescape %}`` tag.27- Flask inserts a couple of global functions and helpers into the

Merge branch 'stable'David Lordbefore adoption3301232

line 28why, one step back
28 Jinja context, additionally to the values that are present by

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 29–33why, one step back
29 default.
3031Standard Context32----------------33

Merge branch 'stable'David Lordbefore adoption3301232

line 34why, one step back
34The following global variables are available within Jinja templates

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 35–139why, one step back
35by default:
3637.. data:: config38 :noindex:3940 The current configuration object (:data:`flask.Flask.config`)4142 .. versionadded:: 0.64344 .. versionchanged:: 0.1045 This is now always available, even in imported templates.4647.. data:: request48 :noindex:4950 The current request object (:class:`flask.request`). This variable is51 unavailable if the template was rendered without an active request52 context.5354.. data:: session55 :noindex:5657 The current session object (:class:`flask.session`). This variable58 is unavailable if the template was rendered without an active request59 context.6061.. data:: g62 :noindex:6364 The request-bound object for global variables (:data:`flask.g`). This65 variable is unavailable if the template was rendered without an active66 request context.6768.. function:: url_for69 :noindex:7071 The :func:`flask.url_for` function.7273.. function:: get_flashed_messages74 :noindex:7576 The :func:`flask.get_flashed_messages` function.7778.. admonition:: The Jinja Context Behavior7980 These variables are added to the context of variables, they are not81 global variables. The difference is that by default these will not82 show up in the context of imported templates. This is partially caused83 by performance considerations, partially to keep things explicit.8485 What does this mean for you? If you have a macro you want to import,86 that needs to access the request object you have two possibilities:8788 1. you explicitly pass the request to the macro as parameter, or89 the attribute of the request object you are interested in.90 2. you import the macro "with context".9192 Importing with context looks like this:9394 .. sourcecode:: jinja9596 {% from '_helpers.html' import my_macro with context %}979899Controlling Autoescaping100------------------------101102Autoescaping is the concept of automatically escaping special characters103for you. Special characters in the sense of HTML (or XML, and thus XHTML)104are ``&``, ``>``, ``<``, ``"`` as well as ``'``. Because these characters105carry specific meanings in documents on their own you have to replace them106by so called "entities" if you want to use them for text. Not doing so107would not only cause user frustration by the inability to use these108characters in text, but can also lead to security problems. (see109:ref:`security-xss`)110111Sometimes however you will need to disable autoescaping in templates.112This can be the case if you want to explicitly inject HTML into pages, for113example if they come from a system that generates secure HTML like a114markdown to HTML converter.115116There are three ways to accomplish that:117118- In the Python code, wrap the HTML string in a :class:`~markupsafe.Markup`119 object before passing it to the template. This is in general the120 recommended way.121- Inside the template, use the ``|safe`` filter to explicitly mark a122 string as safe HTML (``{{ myvariable|safe }}``)123- Temporarily disable the autoescape system altogether.124125To disable the autoescape system in templates, you can use the ``{%126autoescape %}`` block:127128.. sourcecode:: html+jinja129130 {% autoescape false %}131 <p>autoescaping is disabled here132 <p>{{ will_not_be_escaped }}133 {% endautoescape %}134135Whenever you do this, please be very cautious about the variables you are136using in this block.137138.. _registering-filters:139

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

lines 140–141why, one step back
140Registering Filters, Tests, and Globals
141---------------------------------------

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 142why, one step back
142

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

lines 143–145why, one step back
143The Flask app and blueprints provide decorators and methods to register your own
144filters, tests, and global functions for use in Jinja templates. They all follow145the same pattern, so the following examples only discuss filters.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 146why, one step back
146

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

lines 147–148why, one step back
147Decorate a function with :meth:`~.Flask.template_filter` to register it as a
148template filter.

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 149why, one step back
149

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

lines 150–166why, one step back
150.. code-block:: python
151152 @app.template_filter153 def reverse(s):154 return reversed(s)155156.. code-block:: jinja157158 {% for item in data | reverse %}159 {% endfor %}160161By default it will use the name of the function as the name of the filter, but162that can be changed by passing a name to the decorator.163164.. code-block:: python165166 @app.template_filter("reverse")

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 167why, one step back
167 def reverse_filter(s):

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

line 168why, one step back
168 return reversed(s)

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 169why, one step back
169

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

lines 170–174why, one step back
170A filter can be registered separately using :meth:`~.Flask.add_template_filter`.
171The name is optional and will use the function name if not given.172173.. code-block:: python174

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 175why, one step back
175 def reverse_filter(s):

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

line 176why, one step back
176 return reversed(s)

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 177why, one step back
177

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

line 178why, one step back
178 app.add_template_filter(reverse_filter, "reverse")

Merge branch '2.2.x'David Lordbefore adoption73739a2

line 179why, one step back
179

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

lines 180–185why, one step back
180For template tests, use the :meth:`~.Flask.template_test` decorator or
181:meth:`~.Flask.add_template_test` method. For template global functions, use the182:meth:`~.Flask.template_global` decorator or :meth:`~.Flask.add_template_global`183method.184185The same methods also exist on :class:`.Blueprint`, prefixed with ``app_`` to

fix codespell findingsDavid Lordbefore adoption9b74a90

line 186why, one step back
186indicate that the registered functions will be available to all templates, not

support call template_filter without parens (#5736)David Lordbefore adoptioned1c9e9

lines 187–190why, one step back
187only when rendering from within the blueprint.
188189The Jinja environment is also available as :attr:`~.Flask.jinja_env`. It may be190modified directly, as you would when using Jinja outside Flask.

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 191–239why, one step back
191
192193Context Processors194------------------195196To inject new variables automatically into the context of a template,197context processors exist in Flask. Context processors run before the198template is rendered and have the ability to inject new values into the199template context. A context processor is a function that returns a200dictionary. The keys and values of this dictionary are then merged with201the template context, for all templates in the app::202203 @app.context_processor204 def inject_user():205 return dict(user=g.user)206207The context processor above makes a variable called `user` available in208the template with the value of `g.user`. This example is not very209interesting because `g` is available in templates anyways, but it gives an210idea how this works.211212Variables are not limited to values; a context processor can also make213functions available to templates (since Python allows passing around214functions)::215216 @app.context_processor217 def utility_processor():218 def format_price(amount, currency="€"):219 return f"{amount:.2f}{currency}"220 return dict(format_price=format_price)221222The context processor above makes the `format_price` function available to all223templates::224225 {{ format_price(0.33) }}226227You could also build `format_price` as a template filter (see228:ref:`registering-filters`), but this demonstrates how to pass functions in a229context processor.230231Streaming232---------233234It can be useful to not render the whole template as one complete235string, instead render it as a stream, yielding smaller incremental236strings. This can be used for streaming HTML in chunks to speed up237initial page load, or to save memory when rendering a very large238template.239

Merge branch 'stable'David Lordbefore adoption3301232

line 240why, one step back
240The Jinja template engine supports rendering a template piece

Merge branch '2.2.x'David Lordbefore adoption73739a2

lines 241–253why, one step back
241by piece, returning an iterator of strings. Flask provides the
242:func:`~flask.stream_template` and :func:`~flask.stream_template_string`243functions to make this easier to use.244245.. code-block:: python246247 from flask import stream_template248249 @app.get("/timeline")250 def timeline():251 return stream_template("timeline.html")252253These functions automatically apply the

Merge branch 'stable'David Lordbefore adoption3a9d54f

lines 254–261why, one step back
254:func:`~flask.stream_with_context` wrapper if a request is active, so that
255:data:`.request`, :data:`.session`, and :data:`.g` remain available in the256template.257258More headers cannot be sent after the body has begun. Therefore, you must259make sure all headers are set before starting the response. In particular,260if the template will access ``session``, be sure to do so in the view as261well so that the ``Vary: cookie`` header will be set.