Skip to content
Myr

templating.rst

This file

Path

docs/templating.rst

222 lines · 7.2 KiB

Last changed by

Imply the |safe on tojson in templates and change escaping logicArmin Ronacherbefore adoptionef72b78

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/2/documentation/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``22-   a template has the ability to opt in/out autoescaping with the23    ``{% autoescape %}`` tag.24-   Flask inserts a couple of global functions and helpers into the25    Jinja2 context, additionally to the values that are present by26    default.2728Standard Context29----------------3031The following global variables are available within Jinja2 templates32by default:3334.. data:: config35   :noindex:3637   The current configuration object (:data:`flask.config`)3839   .. versionadded:: 0.64041   .. versionchanged:: 0.1042      This is now always available, even in imported templates.4344.. data:: request45   :noindex:4647   The current request object (:class:`flask.request`).  This variable is48   unavailable if the template was rendered without an active request49   context.5051.. data:: session52   :noindex:5354   The current session object (:class:`flask.session`).  This variable55   is unavailable if the template was rendered without an active request56   context.5758.. data:: g59   :noindex:6061   The request-bound object for global variables (:data:`flask.g`).  This62   variable is unavailable if the template was rendered without an active63   request context.6465.. function:: url_for66   :noindex:6768   The :func:`flask.url_for` function.6970.. function:: get_flashed_messages71   :noindex:7273   The :func:`flask.get_flashed_messages` function.7475.. admonition:: The Jinja Context Behavior7677   These variables are added to the context of variables, they are not78   global variables.  The difference is that by default these will not79   show up in the context of imported templates.  This is partially caused80   by performance considerations, partially to keep things explicit.8182   What does this mean for you?  If you have a macro you want to import,83   that needs to access the request object you have two possibilities:8485   1.   you explicitly pass the request to the macro as parameter, or86        the attribute of the request object you are interested in.87   2.   you import the macro "with context".8889   Importing with context looks like this:9091   .. sourcecode:: jinja9293      {% from '_helpers.html' import my_macro with context %}9495Standard Filters96----------------9798These filters are available in Jinja2 additionally to the filters provided99by Jinja2 itself:100101.. function:: tojson102   :noindex:103104   This function converts the given object into JSON representation.  This105   is for example very helpful if you try to generate JavaScript on the106   fly.107108   Note that inside `script` tags no escaping must take place, so make109   sure to disable escaping with ``|safe`` before Flask 0.10 if you intend110   to use it inside `script` tags:111112   .. sourcecode:: html+jinja113114       <script type=text/javascript>115           doSomethingWith({{ user.username|tojson|safe }});116       </script>117118Controlling Autoescaping119------------------------120121Autoescaping is the concept of automatically escaping special characters122of you.  Special characters in the sense of HTML (or XML, and thus XHTML)123are ``&``, ``>``, ``<``, ``"`` as well as ``'``.  Because these characters124carry specific meanings in documents on their own you have to replace them125by so called "entities" if you want to use them for text.  Not doing so126would not only cause user frustration by the inability to use these127characters in text, but can also lead to security problems.  (see128:ref:`xss`)129130Sometimes however you will need to disable autoescaping in templates.131This can be the case if you want to explicitly inject HTML into pages, for132example if they come from a system that generate secure HTML like a133markdown to HTML converter.134135There are three ways to accomplish that:136137-   In the Python code, wrap the HTML string in a :class:`~flask.Markup`138    object before passing it to the template.  This is in general the139    recommended way.140-   Inside the template, use the ``|safe`` filter to explicitly mark a141    string as safe HTML (``{{ myvariable|safe }}``)142-   Temporarily disable the autoescape system altogether.143144To disable the autoescape system in templates, you can use the ``{%145autoescape %}`` block:146147.. sourcecode:: html+jinja148149    {% autoescape false %}150        <p>autoescaping is disabled here151        <p>{{ will_not_be_escaped }}152    {% endautoescape %}153154Whenever you do this, please be very cautious about the variables you are155using in this block.156157.. _registering-filters:158159Registering Filters160-------------------161162If you want to register your own filters in Jinja2 you have two ways to do163that.  You can either put them by hand into the164:attr:`~flask.Flask.jinja_env` of the application or use the165:meth:`~flask.Flask.template_filter` decorator.166167The two following examples work the same and both reverse an object::168169    @app.template_filter('reverse')170    def reverse_filter(s):171        return s[::-1]172173    def reverse_filter(s):174        return s[::-1]175    app.jinja_env.filters['reverse'] = reverse_filter176177In case of the decorator the argument is optional if you want to use the178function name as name of the filter.  Once registered, you can use the filter179in your templates in the same way as Jinja2's builtin filters, for example if180you have a Python list in context called `mylist`::181182    {% for x in mylist | reverse %}183    {% endfor %}184185186Context Processors187------------------188189To inject new variables automatically into the context of a template,190context processors exist in Flask.  Context processors run before the191template is rendered and have the ability to inject new values into the192template context.  A context processor is a function that returns a193dictionary.  The keys and values of this dictionary are then merged with194the template context, for all templates in the app::195196    @app.context_processor197    def inject_user():198        return dict(user=g.user)199200The context processor above makes a variable called `user` available in201the template with the value of `g.user`.  This example is not very202interesting because `g` is available in templates anyways, but it gives an203idea how this works.204205Variables are not limited to values; a context processor can also make206functions available to templates (since Python allows passing around207functions)::208209    @app.context_processor210    def utility_processor():211        def format_price(amount, currency=u'€'):212            return u'{0:.2f}{1}'.format(amount, currency)213        return dict(format_price=format_price)214215The context processor above makes the `format_price` function available to all216templates::217218    {{ format_price(0.33) }}219220You could also build `format_price` as a template filter (see221:ref:`registering-filters`), but this demonstrates how to pass functions in a222context processor.