Skip to content
Myr

templating.rst

This file

Path

docs/templating.rst

229 lines · 7.6 KiB

Last changed by

Merge pull request #4996 from pallets/deprecate-markupsafe-exportDavid Lordbefore adoption704b689

History of this file

Take it

1Templates2=========34Flask leverages Jinja2 as its template engine.  You are obviously free to use5a different template engine, but you still have to install Jinja2 to run6Flask itself.  This requirement is necessary to enable rich extensions.7An extension can depend on Jinja2 being present.89This section only gives a very quick introduction into how Jinja210is integrated into Flask.  If you want information on the template11engine's syntax itself, head over to the official `Jinja2 Template12Documentation <https://jinja.palletsprojects.com/templates/>`_ for13more information.1415Jinja Setup16-----------1718Unless customized, Jinja2 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    Jinja2 context, additionally to the values that are present by29    default.3031Standard Context32----------------3334The following global variables are available within Jinja2 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 Filters141-------------------142143If you want to register your own filters in Jinja2 you have two ways to do144that.  You can either put them by hand into the145:attr:`~flask.Flask.jinja_env` of the application or use the146:meth:`~flask.Flask.template_filter` decorator.147148The two following examples work the same and both reverse an object::149150    @app.template_filter('reverse')151    def reverse_filter(s):152        return s[::-1]153154    def reverse_filter(s):155        return s[::-1]156    app.jinja_env.filters['reverse'] = reverse_filter157158In case of the decorator the argument is optional if you want to use the159function name as name of the filter.  Once registered, you can use the filter160in your templates in the same way as Jinja2's builtin filters, for example if161you have a Python list in context called `mylist`::162163    {% for x in mylist | reverse %}164    {% endfor %}165166167Context Processors168------------------169170To inject new variables automatically into the context of a template,171context processors exist in Flask.  Context processors run before the172template is rendered and have the ability to inject new values into the173template context.  A context processor is a function that returns a174dictionary.  The keys and values of this dictionary are then merged with175the template context, for all templates in the app::176177    @app.context_processor178    def inject_user():179        return dict(user=g.user)180181The context processor above makes a variable called `user` available in182the template with the value of `g.user`.  This example is not very183interesting because `g` is available in templates anyways, but it gives an184idea how this works.185186Variables are not limited to values; a context processor can also make187functions available to templates (since Python allows passing around188functions)::189190    @app.context_processor191    def utility_processor():192        def format_price(amount, currency="€"):193            return f"{amount:.2f}{currency}"194        return dict(format_price=format_price)195196The context processor above makes the `format_price` function available to all197templates::198199    {{ format_price(0.33) }}200201You could also build `format_price` as a template filter (see202:ref:`registering-filters`), but this demonstrates how to pass functions in a203context processor.204205Streaming206---------207208It can be useful to not render the whole template as one complete209string, instead render it as a stream, yielding smaller incremental210strings. This can be used for streaming HTML in chunks to speed up211initial page load, or to save memory when rendering a very large212template.213214The Jinja2 template engine supports rendering a template piece215by piece, returning an iterator of strings. Flask provides the216:func:`~flask.stream_template` and :func:`~flask.stream_template_string`217functions to make this easier to use.218219.. code-block:: python220221    from flask import stream_template222223    @app.get("/timeline")224    def timeline():225        return stream_template("timeline.html")226227These functions automatically apply the228:func:`~flask.stream_with_context` wrapper if a request is active, so229that it remains available in the template.