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 fileTake it
1Templates2=========34Flask leverages Jinja as its template engine. You are obviously free to use5a different template engine, but you still have to install Jinja to run6Flask itself. This requirement is necessary to enable rich extensions.7An extension can depend on Jinja being present.89This section only gives a very quick introduction into how Jinja10is integrated into Flask. If you want information on the template11engine's syntax itself, head over to the official `Jinja Template12Documentation <https://jinja.palletsprojects.com/templates/>`_ for13more information.1415Jinja Setup16-----------1718Unless customized, Jinja is configured by Flask as follows:1920- 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 the28 Jinja context, additionally to the values that are present by29 default.3031Standard Context32----------------3334The following global variables are available within Jinja templates35by 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:139140Registering Filters, Tests, and Globals141---------------------------------------142143The Flask app and blueprints provide decorators and methods to register your own144filters, tests, and global functions for use in Jinja templates. They all follow145the same pattern, so the following examples only discuss filters.146147Decorate a function with :meth:`~.Flask.template_filter` to register it as a148template filter.149150.. code-block:: python151152 @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")167 def reverse_filter(s):168 return reversed(s)169170A 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:: python174175 def reverse_filter(s):176 return reversed(s)177178 app.add_template_filter(reverse_filter, "reverse")179180For template tests, use the :meth:`~.Flask.template_test` decorator or181: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_`` to186indicate that the registered functions will be available to all templates, not187only 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.191192193Context 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.239240The Jinja template engine supports rendering a template piece241by piece, returning an iterator of strings. Flask provides the242: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 the254:func:`~flask.stream_with_context` wrapper if a request is active, so that255: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.