Skip to content
Myr

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

6 files+97 added−3 removed

modified:docs/api.rst+12 added
563 unmodified lines
564``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.567568``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``.575576``json.dumps_kwargs``:577 Keyword arguments to be passed to the dump function. The default is578 ``{'sort_keys': True}``.579580581Utilities582---------583584These helper functions and classes are useful if you add custom filters or
305 unmodified lines
modified:jinja2/defaults.py+4 added-2 removed
39 unmodified lines
404142# default policies43DEFAULT_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}495051# export all constants
1 unmodified line
modified:jinja2/filters.py+35 added-1 removed
13 unmodified lines
14from random import choice15from itertools import groupby16from collections import namedtuple17from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \18 unicode_urlencode18 unicode_urlencode, htmlsafe_json_dumps19from jinja2.runtime import Undefined20from jinja2.exceptions import FilterArgumentError21from jinja2._compat import imap, string_types, text_type, iteritems22
892 unmodified lines
915 """916 return select_or_reject(args, kwargs, lambda x: not x, True)917918919@evalcontextfilter920def 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.926927 The following characters are escaped in strings:928929 - ``<``930 - ``>``931 - ``&``932 - ``'``933934 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.937938 The indent parameter can be used to enable pretty printing. Set it to939 the number of spaces that the structures should be indented with.940941 .. 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)950951952def prepare_map(args, kwargs):953 context = args[0]954 seq = args[1]955
97 unmodified lines
1053 '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 lines
8 :copyright: (c) 2010 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import re12import json13import errno14from collections import deque15from threading import Lock16from jinja2._compat import text_type, string_types, implements_iterator, \
20 unmodified lines
37internal_code = set()3839concat = u''.join4041_slash_escape = '\\/' not in json.dumps('/')424344def 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 access
439 unmodified lines
487except ImportError:488 pass489490491def 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.497498 The following characters are escaped in strings:499500 - ``<``501 - ``>``502 - ``&``503 - ``'``504505 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 rv517518519@implements_iterator520class Cycler(object):521 """A cycle helper for templates."""522
48 unmodified lines
modified:tests/test_filters.py+13 added
574 unmodified lines
575 ]576 tmpl = env.from_string('{{ users|rejectattr("id", "odd")|'577 'map(attribute="name")|join("|") }}')578 assert tmpl.render(users=users) == 'jane'579580 def test_json_dump(self):581 env = Environment(autoescape=True)582 t = env.from_string('{{ x|tojson }}')583 assert t.render(x={'foo': 'bar'}) == '{&#34;foo&#34;: &#34;bar&#34;}'584 assert t.render(x='"bar\'') == '&#34;\&#34;bar\u0027&#34;'585586 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 lines
24- 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.3031Version 2.8.232-------------33
381 unmodified lines