use Jinja's tojson filter

This commit is contained in:
David Lord 2021-02-01 22:41:49 -08:00
parent fdf5d11b51
commit b473e7c97c
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
7 changed files with 28 additions and 88 deletions

View file

@ -60,27 +60,9 @@ like this:
.. sourcecode:: html+jinja
<script type=text/javascript>
$SCRIPT_ROOT = {{ request.script_root|tojson|safe }};
$SCRIPT_ROOT = {{ request.script_root|tojson }};
</script>
The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not
escape the JSON encoded string with HTML rules. Usually this would be
necessary, but we are inside a ``script`` block here where different rules
apply.
.. admonition:: Information for Pros
In HTML the ``script`` tag is declared ``CDATA`` which means that entities
will not be parsed. Everything until ``</script>`` is handled as script.
This also means that there must never be any ``</`` between the script
tags. ``|tojson`` is kind enough to do the right thing here and
escape slashes for you (``{{ "</script>"|tojson|safe }}`` is rendered as
``"<\/script>"``).
In Flask 0.10 it goes a step further and escapes all HTML tags with
unicode escapes. This makes it possible for Flask to automatically
mark the result as HTML safe.
JSON View Functions
-------------------