Skip to content
Myr

Added templating docs. This basically fixes #92

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent fd06bcf · Browse files · 4 files+200 added−1 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+200 added−1 removed

  • other:+200 added−1 removed

4 files+200 added−1 removed

modified:docs/contents.rst.inc+1 added
10 unmodified lines
11 foreword12 installation13 quickstart14 tutorial/index15 templating16 testing17 errorhandling18 config19 signals
33 unmodified lines
modified:docs/quickstart.rst+2 added-1 removed
377 unmodified lines
378 /templates379 /hello.html380381For templates you can use the full power of Jinja2 templates. Head over382to the :ref:`templating` section of the documentation or the official382to the `Jinja2 Template Documentation383`Jinja2 Template Documentation384<http://jinja.pocoo.org/2/documentation/templates>`_ for more information.385386Here an example template:387
361 unmodified lines
modified:docs/security.rst+9 added
3 unmodified lines
4Web applications usually face all kinds of security problems and it's very5hard to get everything right. Flask tries to solve a few of these things6for you, but there are a couple more you have to take care of yourself.78.. _xss:910Cross-Site Scripting (XSS)11--------------------------1213Cross site scripting is the concept of injecting arbitrary HTML (and with14it JavaScript) into the context of a website. To rememdy this, developers15have to properly escape text so that it cannot include arbitrary HTML16tags. For more information on that have a look at the Wikipedia article17on `Cross-Site Scripting18<http://en.wikipedia.org/wiki/Cross-site_scripting>`_.1920Flask configures Jinja2 to automatically escape all values unless21explicitly told otherwise. This should rule out all XSS problems caused22in templates, but there are still other places where you have to be23careful:
120 unmodified lines
added:docs/templating.rst+188 added
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 Behaviour6768 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 varibles you are148using in this block.149150Registering Filters151-------------------152153If you want to register your own filters in Jinja2 you have two ways to do154that. You can either put them by hand into the155:attr:`~flask.Flask.jinja_env` of the application or use the156:meth:`~flask.Flask.template_filter` decorator.157158The two following examples work the same and both reverse an object::159160 @app.template_filter('reverse')161 def reverse_filter(s):162 return s[::-1]163164 def reverse_filter(s):165 return s[::-1]166 app.jinja_env.filters['reverse'] = reverse_filter167168In case of the decorator the argument is optional if you want to use the169function name as name of the filter.170171Context Processors172------------------173174To inject new variables automatically into the context of a template175context processors exist in Flask. Context processors run before the176template is rendered and have the ability to inject new values into the177template context. A context processor is a function that returns a178dictionary. The keys and values of this dictionary are then merged with179the template context::180181 @app.context_processor182 def inject_user():183 return dict(user=g.user)184185The context processor above makes a variable called `user` available in186the template with the value of `g.user`. This example is not very187interesting because `g` is available in templates anyways, but it gives an188idea how this works.