Skip to content
Myr

templating.rst

This file

Path

docs/templating.rst

225 lines · 7.4 KiB

Last changed by

Merge pull request #1607 from wodim/patch-1Armin Ronacherbefore adoption5c73a8b

History of this file

Take it

1Templates2=========34Flask leverages Jinja2 as 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 <http://jinja.pocoo.org/docs/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`` as well as ``.xhtml`` 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.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 %}9798Standard Filters99----------------100101These filters are available in Jinja2 additionally to the filters provided102by Jinja2 itself:103104.. function:: tojson105   :noindex:106107   This function converts the given object into JSON representation.  This108   is for example very helpful if you try to generate JavaScript on the109   fly.110111   Note that inside ``script`` tags no escaping must take place, so make112   sure to disable escaping with ``|safe`` before Flask 0.10 if you intend113   to use it inside ``script`` tags:114115   .. sourcecode:: html+jinja116117       <script type=text/javascript>118           doSomethingWith({{ user.username|tojson|safe }});119       </script>120121Controlling Autoescaping122------------------------123124Autoescaping is the concept of automatically escaping special characters125for you.  Special characters in the sense of HTML (or XML, and thus XHTML)126are ``&``, ``>``, ``<``, ``"`` as well as ``'``.  Because these characters127carry specific meanings in documents on their own you have to replace them128by so called "entities" if you want to use them for text.  Not doing so129would not only cause user frustration by the inability to use these130characters in text, but can also lead to security problems.  (see131:ref:`xss`)132133Sometimes however you will need to disable autoescaping in templates.134This can be the case if you want to explicitly inject HTML into pages, for135example if they come from a system that generates secure HTML like a136markdown to HTML converter.137138There are three ways to accomplish that:139140-   In the Python code, wrap the HTML string in a :class:`~flask.Markup`141    object before passing it to the template.  This is in general the142    recommended way.143-   Inside the template, use the ``|safe`` filter to explicitly mark a144    string as safe HTML (``{{ myvariable|safe }}``)145-   Temporarily disable the autoescape system altogether.146147To disable the autoescape system in templates, you can use the ``{%148autoescape %}`` block:149150.. sourcecode:: html+jinja151152    {% autoescape false %}153        <p>autoescaping is disabled here154        <p>{{ will_not_be_escaped }}155    {% endautoescape %}156157Whenever you do this, please be very cautious about the variables you are158using in this block.159160.. _registering-filters:161162Registering Filters163-------------------164165If you want to register your own filters in Jinja2 you have two ways to do166that.  You can either put them by hand into the167:attr:`~flask.Flask.jinja_env` of the application or use the168:meth:`~flask.Flask.template_filter` decorator.169170The two following examples work the same and both reverse an object::171172    @app.template_filter('reverse')173    def reverse_filter(s):174        return s[::-1]175176    def reverse_filter(s):177        return s[::-1]178    app.jinja_env.filters['reverse'] = reverse_filter179180In case of the decorator the argument is optional if you want to use the181function name as name of the filter.  Once registered, you can use the filter182in your templates in the same way as Jinja2's builtin filters, for example if183you have a Python list in context called `mylist`::184185    {% for x in mylist | reverse %}186    {% endfor %}187188189Context Processors190------------------191192To inject new variables automatically into the context of a template,193context processors exist in Flask.  Context processors run before the194template is rendered and have the ability to inject new values into the195template context.  A context processor is a function that returns a196dictionary.  The keys and values of this dictionary are then merged with197the template context, for all templates in the app::198199    @app.context_processor200    def inject_user():201        return dict(user=g.user)202203The context processor above makes a variable called `user` available in204the template with the value of `g.user`.  This example is not very205interesting because `g` is available in templates anyways, but it gives an206idea how this works.207208Variables are not limited to values; a context processor can also make209functions available to templates (since Python allows passing around210functions)::211212    @app.context_processor213    def utility_processor():214        def format_price(amount, currency=u'€'):215            return u'{0:.2f}{1}'.format(amount, currency)216        return dict(format_price=format_price)217218The context processor above makes the `format_price` function available to all219templates::220221    {{ format_price(0.33) }}222223You could also build `format_price` as a template filter (see224:ref:`registering-filters`), but this demonstrates how to pass functions in a225context processor.