templating.rst
This file
Path
docs/templating.rst
215 lines · 6.9 KiB
Last changed by
Use American English for "behavior" in docs.Ron DuPlainbefore adoptiona3cb2a3
History of this fileTake 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.. data:: request42 :noindex:4344 The current request object (:class:`flask.request`)4546.. data:: session47 :noindex:4849 The current session object (:class:`flask.session`)5051.. data:: g52 :noindex:5354 The request-bound object for global variables (:data:`flask.g`)5556.. function:: url_for57 :noindex:5859 The :func:`flask.url_for` function.6061.. function:: get_flashed_messages62 :noindex:6364 The :func:`flask.get_flashed_messages` function.6566.. admonition:: The Jinja Context Behavior6768 These variables are added to the context of variables, they are not69 global variables. The difference is that by default these will not70 show up in the context of imported templates. This is partially caused71 by performance considerations, partially to keep things explicit.7273 What does this mean for you? If you have a macro you want to import,74 that needs to access the request object you have two possibilities:7576 1. you explicitly pass the request to the macro as parameter, or77 the attribute of the request object you are interested in.78 2. you import the macro "with context".7980 Importing with context looks like this:8182 .. sourcecode:: jinja8384 {% from '_helpers.html' import my_macro with context %}8586Standard Filters87----------------8889These filters are available in Jinja2 additionally to the filters provided90by Jinja2 itself:9192.. function:: tojson93 :noindex:9495 This function converts the given object into JSON representation. This96 is for example very helpful if you try to generate JavaScript on the97 fly.9899 Note that inside `script` tags no escaping must take place, so make100 sure to disable escaping with ``|safe`` if you intend to use it inside101 `script` tags:102103 .. sourcecode:: html+jinja104105 <script type=text/javascript>106 doSomethingWith({{ user.username|tojson|safe }});107 </script>108109 That the ``|tojson`` filter escapes forward slashes properly for you.110111Controlling Autoescaping112------------------------113114Autoescaping is the concept of automatically escaping special characters115of you. Special characters in the sense of HTML (or XML, and thus XHTML)116are ``&``, ``>``, ``<``, ``"`` as well as ``'``. Because these characters117carry specific meanings in documents on their own you have to replace them118by so called "entities" if you want to use them for text. Not doing so119would not only cause user frustration by the inability to use these120characters in text, but can also lead to security problems. (see121:ref:`xss`)122123Sometimes however you will need to disable autoescaping in templates.124This can be the case if you want to explicitly inject HTML into pages, for125example if they come from a system that generate secure HTML like a126markdown to HTML converter.127128There are three ways to accomplish that:129130- In the Python code, wrap the HTML string in a :class:`~flask.Markup`131 object before passing it to the template. This is in general the132 recommended way.133- Inside the template, use the ``|safe`` filter to explicitly mark a134 string as safe HTML (``{{ myvariable|safe }}``)135- Temporarily disable the autoescape system altogether.136137To disable the autoescape system in templates, you can use the ``{%138autoescape %}`` block:139140.. sourcecode:: html+jinja141142 {% autoescape false %}143 <p>autoescaping is disabled here144 <p>{{ will_not_be_escaped }}145 {% endautoescape %}146147Whenever you do this, please be very cautious about the variables you are148using in this block.149150.. _registering-filters:151152Registering Filters153-------------------154155If you want to register your own filters in Jinja2 you have two ways to do156that. You can either put them by hand into the157:attr:`~flask.Flask.jinja_env` of the application or use the158:meth:`~flask.Flask.template_filter` decorator.159160The two following examples work the same and both reverse an object::161162 @app.template_filter('reverse')163 def reverse_filter(s):164 return s[::-1]165166 def reverse_filter(s):167 return s[::-1]168 app.jinja_env.filters['reverse'] = reverse_filter169170In case of the decorator the argument is optional if you want to use the171function name as name of the filter. Once registered, you can use the filter172in your templates in the same way as Jinja2's builtin filters, for example if173you have a Python list in context called `mylist`::174175 {% for x in mylist | reverse %}176 {% endfor %}177178179Context Processors180------------------181182To inject new variables automatically into the context of a template183context processors exist in Flask. Context processors run before the184template is rendered and have the ability to inject new values into the185template context. A context processor is a function that returns a186dictionary. The keys and values of this dictionary are then merged with187the template context, for all templates in the app::188189 @app.context_processor190 def inject_user():191 return dict(user=g.user)192193The context processor above makes a variable called `user` available in194the template with the value of `g.user`. This example is not very195interesting because `g` is available in templates anyways, but it gives an196idea how this works.197198Variables are not limited to values; a context processor can also make199functions available to templates (since Python allows passing around200functions)::201202 @app.context_processor203 def utility_processor():204 def format_price(amount, currency=u'€'):205 return u'{0:.2f}{1}.format(amount, currency)206 return dict(format_price=format_price)207208The context processor above makes the `format_price` function available to all209templates::210211 {{ format_price(0.33) }}212213You could also build `format_price` as a template filter (see214:ref:`registering-filters`), but this demonstrates how to pass functions in a215context processor.