Skip to content
Myr

templating.rst

This file

Path

docs/templating.rst

236 lines · 7.6 KiB

Last changed by

Merge branch '1.0-maintenance'David Lordbefore adoption3b45b82

History of this file

Take it

1.. _templates:23Templates4=========56Flask leverages Jinja2 as template engine.  You are obviously free to use7a different template engine, but you still have to install Jinja2 to run8Flask itself.  This requirement is necessary to enable rich extensions.9An extension can depend on Jinja2 being present.1011This section only gives a very quick introduction into how Jinja212is integrated into Flask.  If you want information on the template13engine's syntax itself, head over to the official `Jinja2 Template14Documentation <http://jinja.pocoo.org/docs/templates>`_ for15more information.1617Jinja Setup18-----------1920Unless customized, Jinja2 is configured by Flask as follows:2122-   autoescaping is enabled for all templates ending in ``.html``,23    ``.htm``, ``.xml`` as well as ``.xhtml`` when using24    :func:`~flask.templating.render_template`.25-   autoescaping is enabled for all strings when using26    :func:`~flask.templating.render_template_string`.27-   a template has the ability to opt in/out autoescaping with the28    ``{% autoescape %}`` tag.29-   Flask inserts a couple of global functions and helpers into the30    Jinja2 context, additionally to the values that are present by31    default.3233Standard Context34----------------3536The following global variables are available within Jinja2 templates37by default:3839.. data:: config40   :noindex:4142   The current configuration object (:data:`flask.config`)4344   .. versionadded:: 0.64546   .. versionchanged:: 0.1047      This is now always available, even in imported templates.4849.. data:: request50   :noindex:5152   The current request object (:class:`flask.request`).  This variable is53   unavailable if the template was rendered without an active request54   context.5556.. data:: session57   :noindex:5859   The current session object (:class:`flask.session`).  This variable60   is unavailable if the template was rendered without an active request61   context.6263.. data:: g64   :noindex:6566   The request-bound object for global variables (:data:`flask.g`).  This67   variable is unavailable if the template was rendered without an active68   request context.6970.. function:: url_for71   :noindex:7273   The :func:`flask.url_for` function.7475.. function:: get_flashed_messages76   :noindex:7778   The :func:`flask.get_flashed_messages` function.7980.. admonition:: The Jinja Context Behavior8182   These variables are added to the context of variables, they are not83   global variables.  The difference is that by default these will not84   show up in the context of imported templates.  This is partially caused85   by performance considerations, partially to keep things explicit.8687   What does this mean for you?  If you have a macro you want to import,88   that needs to access the request object you have two possibilities:8990   1.   you explicitly pass the request to the macro as parameter, or91        the attribute of the request object you are interested in.92   2.   you import the macro "with context".9394   Importing with context looks like this:9596   .. sourcecode:: jinja9798      {% from '_helpers.html' import my_macro with context %}99100Standard Filters101----------------102103These filters are available in Jinja2 additionally to the filters provided104by Jinja2 itself:105106.. function:: tojson107   :noindex:108109   This function converts the given object into JSON representation.  This110   is for example very helpful if you try to generate JavaScript on the111   fly.112113   .. sourcecode:: html+jinja114115       <script type=text/javascript>116           doSomethingWith({{ user.username|tojson }});117       </script>118119   It is also safe to use the output of `|tojson` in a *single-quoted* HTML120   attribute:121122   .. sourcecode:: html+jinja123124       <button onclick='doSomethingWith({{ user.username|tojson }})'>125           Click me126       </button>127128   Note that in versions of Flask prior to 0.10, if using the output of129   ``|tojson`` inside ``script``, make sure to disable escaping with ``|safe``.130   In Flask 0.10 and above, this happens automatically.131132Controlling Autoescaping133------------------------134135Autoescaping is the concept of automatically escaping special characters136for you.  Special characters in the sense of HTML (or XML, and thus XHTML)137are ``&``, ``>``, ``<``, ``"`` as well as ``'``.  Because these characters138carry specific meanings in documents on their own you have to replace them139by so called "entities" if you want to use them for text.  Not doing so140would not only cause user frustration by the inability to use these141characters in text, but can also lead to security problems.  (see142:ref:`xss`)143144Sometimes however you will need to disable autoescaping in templates.145This can be the case if you want to explicitly inject HTML into pages, for146example if they come from a system that generates secure HTML like a147markdown to HTML converter.148149There are three ways to accomplish that:150151-   In the Python code, wrap the HTML string in a :class:`~flask.Markup`152    object before passing it to the template.  This is in general the153    recommended way.154-   Inside the template, use the ``|safe`` filter to explicitly mark a155    string as safe HTML (``{{ myvariable|safe }}``)156-   Temporarily disable the autoescape system altogether.157158To disable the autoescape system in templates, you can use the ``{%159autoescape %}`` block:160161.. sourcecode:: html+jinja162163    {% autoescape false %}164        <p>autoescaping is disabled here165        <p>{{ will_not_be_escaped }}166    {% endautoescape %}167168Whenever you do this, please be very cautious about the variables you are169using in this block.170171.. _registering-filters:172173Registering Filters174-------------------175176If you want to register your own filters in Jinja2 you have two ways to do177that.  You can either put them by hand into the178:attr:`~flask.Flask.jinja_env` of the application or use the179:meth:`~flask.Flask.template_filter` decorator.180181The two following examples work the same and both reverse an object::182183    @app.template_filter('reverse')184    def reverse_filter(s):185        return s[::-1]186187    def reverse_filter(s):188        return s[::-1]189    app.jinja_env.filters['reverse'] = reverse_filter190191In case of the decorator the argument is optional if you want to use the192function name as name of the filter.  Once registered, you can use the filter193in your templates in the same way as Jinja2's builtin filters, for example if194you have a Python list in context called `mylist`::195196    {% for x in mylist | reverse %}197    {% endfor %}198199200Context Processors201------------------202203To inject new variables automatically into the context of a template,204context processors exist in Flask.  Context processors run before the205template is rendered and have the ability to inject new values into the206template context.  A context processor is a function that returns a207dictionary.  The keys and values of this dictionary are then merged with208the template context, for all templates in the app::209210    @app.context_processor211    def inject_user():212        return dict(user=g.user)213214The context processor above makes a variable called `user` available in215the template with the value of `g.user`.  This example is not very216interesting because `g` is available in templates anyways, but it gives an217idea how this works.218219Variables are not limited to values; a context processor can also make220functions available to templates (since Python allows passing around221functions)::222223    @app.context_processor224    def utility_processor():225        def format_price(amount, currency=u'€'):226            return u'{0:.2f}{1}'.format(amount, currency)227        return dict(format_price=format_price)228229The context processor above makes the `format_price` function available to all230templates::231232    {{ format_price(0.33) }}233234You could also build `format_price` as a template filter (see235:ref:`registering-filters`), but this demonstrates how to pass functions in a236context processor.