Ported tojson filter. Fixes #458
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 ffe0caa · Browse files · 6 files·+97 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
6 files+97 added−3 removed
- tests:+13 added−0 removed
- other:+84 added−3 removed
Provenance
- Commit
e71a130- Tree
96f4f93- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
ffe0caa
6 files changed+97 added−3 removed
modified:docs/api.rst+12 added
563 unmodified lines564 ``urlize.target``:565 The default target that is issued for links from the `urlize` filter566 if no other target is defined by the call explicitly.567 568+``json.dumps_function``:569+ If this is set to a value other than `None` then the `tojson` filter570+ will dump with this function instead of the default one. Note that571+ this function should accept arbitrary extra arguments which might be572+ passed in the future from the filter. Currently the only argument573+ that might be passed is `indent`. The default dump function is574+ ``json.dumps``.575 576+``json.dumps_kwargs``:577+ Keyword arguments to be passed to the dump function. The default is578+ ``{'sort_keys': True}``.579+580+581 Utilities582 ---------583 584 These helper functions and classes are useful if you add custom filters or305 unmodified linesmodified:jinja2/defaults.py+4 added-2 removed
39 unmodified lines40 41 42 # default policies43 DEFAULT_POLICIES = {44- 'urlize.rel': 'noopener',45- 'urlize.target': None,44+ 'urlize.rel': 'noopener',45+ 'urlize.target': None,46+ 'json.dumps_function': None,47+ 'json.dumps_kwargs': {'sort_keys': True},48 }49 50 51 # export all constants1 unmodified linemodified:jinja2/filters.py+35 added-1 removed
13 unmodified lines14 from random import choice15 from itertools import groupby16 from collections import namedtuple17 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \18- unicode_urlencode18+ unicode_urlencode, htmlsafe_json_dumps19 from jinja2.runtime import Undefined20 from jinja2.exceptions import FilterArgumentError21 from jinja2._compat import imap, string_types, text_type, iteritems22 892 unmodified lines915 """916 return select_or_reject(args, kwargs, lambda x: not x, True)917 918 919+@evalcontextfilter920+def do_tojson(eval_ctx, value, indent=None):921+ """Dumps a structure to JSON so that it's safe to use in ``<script>``922+ tags. It accepts the same arguments and returns a JSON string. Note that923+ this is available in templates through the ``|tojson`` filter which will924+ also mark the result as safe. Due to how this function escapes certain925+ characters this is safe even if used outside of ``<script>`` tags.926+927+ The following characters are escaped in strings:928+929+ - ``<``930+ - ``>``931+ - ``&``932+ - ``'``933+934+ This makes it safe to embed such strings in any place in HTML with the935+ notable exception of double quoted attributes. In that case single936+ quote your attributes or HTML escape it in addition.937+938+ The indent parameter can be used to enable pretty printing. Set it to939+ the number of spaces that the structures should be indented with.940+941+ .. versionadded:: 2.9942+ """943+ policies = eval_ctx.environment.policies944+ dumper = policies['json.dumps_function']945+ options = policies['json.dumps_kwargs']946+ if indent is not None:947+ options = dict(options)948+ options['indent'] = indent949+ return htmlsafe_json_dumps(value, dumper=dumper, **options)950+951+952 def prepare_map(args, kwargs):953 context = args[0]954 seq = args[1]955 97 unmodified lines1053 'urlize': do_urlize,1054 'wordcount': do_wordcount,1055 'wordwrap': do_wordwrap,1056 'xmlattr': do_xmlattr,1057+ 'tojson': do_tojson,1058 }modified:jinja2/utils.py+31 added
7 unmodified lines8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11 import re12+import json13 import errno14 from collections import deque15 from threading import Lock16 from jinja2._compat import text_type, string_types, implements_iterator, \20 unmodified lines37 internal_code = set()38 39 concat = u''.join40 41+_slash_escape = '\\/' not in json.dumps('/')42 43+44 def contextfunction(f):45 """This decorator can be used to mark a function or method context callable.46 A context callable is passed the active :class:`Context` as first argument when47 called from the template. This is useful if a function wants to get access439 unmodified lines487 except ImportError:488 pass489 490 491+def htmlsafe_json_dumps(obj, dumper=None, **kwargs):492+ """Works exactly like :func:`dumps` but is safe for use in ``<script>``493+ tags. It accepts the same arguments and returns a JSON string. Note that494+ this is available in templates through the ``|tojson`` filter which will495+ also mark the result as safe. Due to how this function escapes certain496+ characters this is safe even if used outside of ``<script>`` tags.497+498+ The following characters are escaped in strings:499+500+ - ``<``501+ - ``>``502+ - ``&``503+ - ``'``504+505+ This makes it safe to embed such strings in any place in HTML with the506+ notable exception of double quoted attributes. In that case single507+ quote your attributes or HTML escape it in addition.508+ """509+ if dumper is None:510+ dumper = json.dumps511+ rv = dumper(obj, **kwargs) \512+ .replace(u'<', u'\\u003c') \513+ .replace(u'>', u'\\u003e') \514+ .replace(u'&', u'\\u0026') \515+ .replace(u"'", u'\\u0027')516+ return rv517+518+519 @implements_iterator520 class Cycler(object):521 """A cycle helper for templates."""522 48 unmodified linesmodified:tests/test_filters.py+13 added
574 unmodified lines575 ]576 tmpl = env.from_string('{{ users|rejectattr("id", "odd")|'577 'map(attribute="name")|join("|") }}')578 assert tmpl.render(users=users) == 'jane'579+580+ def test_json_dump(self):581+ env = Environment(autoescape=True)582+ t = env.from_string('{{ x|tojson }}')583+ assert t.render(x={'foo': 'bar'}) == '{"foo": "bar"}'584+ assert t.render(x='"bar\'') == '"\"bar\u0027"'585+586+ def my_dumps(value, **options):587+ assert options == {'foo': 'bar'}588+ return '42'589+ env.policies['json.dumps_function'] = my_dumps590+ env.policies['json.dumps_kwargs'] = {'foo': 'bar'}591+ assert t.render(x=23) == '42'modified:CHANGES+2 added
23 unmodified lines24 - Improved the `truncate` filter to support better truncation in case25 the string is barely truncated at all.26 - Change the logic for macro autoescaping to be based on the runtime27 autoescaping information at call time instead of macro define time.28+- Ported a modified version of the `tojson` filter from Flask to Jinja229+ and hooked it up with the new policy framework.30 31 Version 2.8.232 -------------33 381 unmodified lines