diff options
| author | Jonas Haag <jonas@lophus.org> | 2017-10-12 20:59:38 +0200 |
|---|---|---|
| committer | Tim Graham <timograham@gmail.com> | 2018-02-07 18:38:12 -0500 |
| commit | 8c709d79cbd1a7bb975f58090c17a1178a0efb80 (patch) | |
| tree | 79e6be4dac2289ca5e4943db9ae071d14f95cdc5 /django/utils/html.py | |
| parent | ef2512b2ffdb719e5c0fb82142f9ce8478282823 (diff) | |
Fixed #17419 -- Added json_tag template filter.
Diffstat (limited to 'django/utils/html.py')
| -rw-r--r-- | django/utils/html.py | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/django/utils/html.py b/django/utils/html.py index e6389d4db5..60f505a4b7 100644 --- a/django/utils/html.py +++ b/django/utils/html.py @@ -1,5 +1,6 @@ """HTML utilities suitable for global use.""" +import json import re from html.parser import HTMLParser from urllib.parse import ( @@ -77,6 +78,27 @@ def escapejs(value): return mark_safe(str(value).translate(_js_escapes)) +_json_script_escapes = { + ord('>'): '\\u003E', + ord('<'): '\\u003C', + ord('&'): '\\u0026', +} + + +def json_script(value, element_id): + """ + Escape all the HTML/XML special characters with their unicode escapes, so + value is safe to be output anywhere except for inside a tag attribute. Wrap + the escaped JSON in a script tag. + """ + from django.core.serializers.json import DjangoJSONEncoder + json_str = json.dumps(value, cls=DjangoJSONEncoder).translate(_json_script_escapes) + return format_html( + '<script id="{}" type="application/json">{}</script>', + element_id, mark_safe(json_str) + ) + + def conditional_escape(text): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. |
