Skip to content

Instantly share code, notes, and snippets.

@edwardfung123
Last active July 13, 2017 11:09
Show Gist options
  • Select an option

  • Save edwardfung123/6bcfac36fa0b77bdd086e4d39b82b486 to your computer and use it in GitHub Desktop.

Select an option

Save edwardfung123/6bcfac36fa0b77bdd086e4d39b82b486 to your computer and use it in GitHub Desktop.
Backporting tojson filter from jinja2.9 to jinja2.6
def htmlsafe_json_dumps(obj, dumper=None, **kwargs):
"""Works exactly like :func:`dumps` but is safe for use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
"""
if dumper is None:
import json
dumper = json.dumps
rv = dumper(obj, **kwargs) \
.replace(u'<', u'\\u003c') \
.replace(u'>', u'\\u003e') \
.replace(u'&', u'\\u0026') \
.replace(u"'", u'\\u0027')
return rv
def getJinja2Environment():
env = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__),encoding='utf-8'),
extensions=['jinja2.ext.autoescape', 'jinja2.ext.with_'],
autoescape=True)
try:
getattr(env, 'policies')
except AttributeError as exception:
import json
policies = {
'json.dumps_function': json.dumps,
'json.dumps_kwargs': {'sort_keys': True},
}
setattr(env, 'policies', policies)
try:
from jinja2.filters import do_tojson
except ImportError as e:
# backport the tojson filter
from jinja2.filters import evalcontextfilter
@evalcontextfilter
def do_tojson(eval_ctx, value, indent=None):
"""Dumps a structure to JSON so that it's safe to use in ``<script>``
tags. It accepts the same arguments and returns a JSON string. Note that
this is available in templates through the ``|tojson`` filter which will
also mark the result as safe. Due to how this function escapes certain
characters this is safe even if used outside of ``<script>`` tags.
The following characters are escaped in strings:
- ``<``
- ``>``
- ``&``
- ``'``
This makes it safe to embed such strings in any place in HTML with the
notable exception of double quoted attributes. In that case single
quote your attributes or HTML escape it in addition.
The indent parameter can be used to enable pretty printing. Set it to
the number of spaces that the structures should be indented with.
Note that this filter is for use in HTML contexts only.
.. versionadded:: 2.9
"""
policies = eval_ctx.environment.policies
dumper = policies['json.dumps_function']
options = policies['json.dumps_kwargs']
if indent is not None:
options = dict(options)
options['indent'] = indent
return htmlsafe_json_dumps(value, dumper=dumper, **options)
env.filters['tojson'] = do_tojson
return env
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment