Skip to content
Myr

Merge pull request #3895 from pallets/jinja-tojson

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

use Jinja's tojson filter

authored by David Lord · committed by GitHub · parents fdf5d11, b473e7c · Browse files · 7 files+28 added−88 removed
This commit

State

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

Diff stats

7 files+28 added−88 removed

  • tests:+10 added−17 removed
  • other:+18 added−71 removed

7 files+28 added−88 removed

modified:docs/patterns/jquery.rst+1 added-19 removed
58 unmodified lines
5960.. sourcecode:: html+jinja6162 <script type=text/javascript>63 $SCRIPT_ROOT = {{ request.script_root|tojson|safe }};63 $SCRIPT_ROOT = {{ request.script_root|tojson }};64 </script>6566The ``|safe`` is necessary in Flask before 0.10 so that Jinja does not67escape the JSON encoded string with HTML rules. Usually this would be68necessary, but we are inside a ``script`` block here where different rules69apply.6671.. admonition:: Information for Pros7273 In HTML the ``script`` tag is declared ``CDATA`` which means that entities74 will not be parsed. Everything until ``</script>`` is handled as script.75 This also means that there must never be any ``</`` between the script76 tags. ``|tojson`` is kind enough to do the right thing here and77 escape slashes for you (``{{ "</script>"|tojson|safe }}`` is rendered as78 ``"<\/script>"``).7980 In Flask 0.10 it goes a step further and escapes all HTML tags with81 unicode escapes. This makes it possible for Flask to automatically82 mark the result as HTML safe.838467JSON View Functions68-------------------6970Now let's create a server side function that accepts two URL arguments of
79 unmodified lines
modified:docs/api.rst+5 added-4 removed
248 unmodified lines
249 :func:`dataclasses.asdict`.250- :class:`~markupsafe.Markup` (or any object with a ``__html__``251 method) will call the ``__html__`` method to get a string.252253:func:`~htmlsafe_dumps` is also available as the ``|tojson`` template254filter. The filter marks the output with ``|safe`` so it can be used255inside ``script`` tags.253Jinja's ``|tojson`` filter is configured to use Flask's :func:`dumps`254function. The filter marks the output with ``|safe`` automatically. Use255the filter to render data inside ``<script>`` tags.256257.. sourcecode:: html+jinja258259 <script type=text/javascript>260 const names = {{ names|tosjon }};260 renderChart({{ axis_data|tojson }});261 renderChart(names, {{ axis_data|tojson }});262 </script>263264.. autofunction:: jsonify265
510 unmodified lines
modified:docs/templating.rst-31 removed
93 unmodified lines
94 .. sourcecode:: jinja9596 {% from '_helpers.html' import my_macro with context %}9798Standard Filters99----------------98101Flask provides the following Jinja2 filters in addition to the filters provided102by Jinja2 itself:103104.. function:: tojson105 :noindex:106107 This function converts the given object into JSON representation. This108 is for example very helpful if you try to generate JavaScript on the109 fly.110111 .. sourcecode:: html+jinja112113 <script type=text/javascript>114 doSomethingWith({{ user.username|tojson }});115 </script>116117 It is also safe to use the output of `|tojson` in a *single-quoted* HTML118 attribute:119120 .. sourcecode:: html+jinja121122 <button onclick='doSomethingWith({{ user.username|tojson }})'>123 Click me124 </button>125126 Note that in versions of Flask prior to 0.10, if using the output of127 ``|tojson`` inside ``script``, make sure to disable escaping with ``|safe``.128 In Flask 0.10 and above, this happens automatically.12999Controlling Autoescaping100------------------------101102Autoescaping is the concept of automatically escaping special characters
101 unmodified lines
modified:src/flask/json/__init__.py+10 added-16 removed
3 unmodified lines
4import warnings5from datetime import date6from datetime import datetime78from markupsafe import Markup8from jinja2.utils import htmlsafe_json_dumps as _jinja_htmlsafe_dumps9from werkzeug.http import http_date1011from ..globals import current_app12from ..globals import request
220 unmodified lines
233234 return _json.load(fp, **kwargs)235236237_htmlsafe_map = str.maketrans(238 {"<": "\\u003c", ">": "\\u003e", "&": "\\u0026", "'": "\\u0027"}239)240241237def htmlsafe_dumps(obj, **kwargs):243 """Serialize an object to a string of JSON, replacing HTML-unsafe244 characters with Unicode escapes. Otherwise behaves the same as245 :func:`dumps`.238 """Serialize an object to a string of JSON with :func:`dumps`, then239 replace HTML-unsafe characters with Unicode escapes and mark the240 result safe with :class:`~markupsafe.Markup`.241247 This is available in templates as the ``|tojson`` filter, which will248 also mark the result with ``|safe``.242 This is available in templates as the ``|tojson`` filter.243244 The returned string is safe to render in HTML documents and245 ``<script>`` tags. The exception is in HTML attributes that are246 double quoted; either use single quotes or the ``|forceescape``247 filter.248249 .. versionchanged:: 2.0250 Uses :func:`jinja2.utils.htmlsafe_json_dumps`. The returned251 value is marked safe by wrapping in :class:`~markupsafe.Markup`.252253 .. versionchanged:: 0.10254 Single quotes are escaped, making this safe to use in HTML,255 ``<script>`` tags, and single-quoted attributes without further256 escaping.257 """260 return dumps(obj, **kwargs).translate(_htmlsafe_map)258 return _jinja_htmlsafe_dumps(obj, dumps=dumps, **kwargs)259260261def htmlsafe_dump(obj, fp, **kwargs):262 """Serialize an object to JSON written to a file object, replacing
69 unmodified lines
332 return current_app.response_class(333 f"{dumps(data, indent=indent, separators=separators)}\n",334 mimetype=current_app.config["JSONIFY_MIMETYPE"],335 )338339340def tojson_filter(obj, **kwargs):341 return Markup(htmlsafe_dumps(obj, **kwargs))
modified:src/flask/app.py+1 added-1 removed
679 unmodified lines
680 request=request,681 session=session,682 g=g,683 )684 rv.filters["tojson"] = json.tojson_filter684 rv.policies["json.dumps_function"] = json.dumps685 return rv686687 def create_global_jinja_loader(self):688 """Creates the loader for the Jinja2 environment. Can be used to
1344 unmodified lines
modified:tests/test_json.py+10 added-17 removed
202 unmodified lines
203 )204 assert rv.data == b"3"205206207def test_template_escaping(app, req_ctx):208 render = flask.render_template_string209 rv = flask.json.htmlsafe_dumps("</script>")210 assert rv == '"\\u003c/script\\u003e"'211 rv = render('{{ "</script>"|tojson }}')212 assert rv == '"\\u003c/script\\u003e"'213 rv = render('{{ "<\0/script>"|tojson }}')214 assert rv == '"\\u003c\\u0000/script\\u003e"'215 rv = render('{{ "<!--<script>"|tojson }}')216 assert rv == '"\\u003c!--\\u003cscript\\u003e"'217 rv = render('{{ "&"|tojson }}')218 assert rv == '"\\u0026"'219 rv = render('{{ "\'"|tojson }}')220 assert rv == '"\\u0027"'221 rv = render(222 "<a ng-data='{{ data|tojson }}'></a>", data={"x": ["foo", "bar", "baz'"]}207def test_tojson_filter(app, req_ctx):208 # The tojson filter is tested in Jinja, this confirms that it's209 # using Flask's dumps.210 rv = flask.render_template_string(211 "const data = {{ data|tojson }};",212 data={"name": "</script>", "time": datetime.datetime(2021, 2, 1, 7, 15)},213 )224 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'214 assert rv == (215 'const data = {"name": "\\u003c/script\\u003e",'216 ' "time": "Mon, 01 Feb 2021 07:15:00 GMT"};'217 )218219220def test_json_customization(app, client):221 class X: # noqa: B903, for Python2 compatibility
184 unmodified lines
modified:CHANGES.rst+1 added
61 unmodified lines
62 ``werkzeug.utils.safe_join`` instead. :pr:`3828`63- The request context does route matching before opening the session.64 This could allow a session interface to change behavior based on65 ``request.endpoint``. :issue:`3776`66- Use Jinja's implementation of the ``|tojson`` filter. :issue:`3881`676869Version 1.1.270-------------
1011 unmodified lines