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.
(value, element_id=None, encoder=None)
| 98 | |
| 99 | |
| 100 | def json_script(value, element_id=None, encoder=None): |
| 101 | """ |
| 102 | Escape all the HTML/XML special characters with their unicode escapes, so |
| 103 | value is safe to be output anywhere except for inside a tag attribute. Wrap |
| 104 | the escaped JSON in a script tag. |
| 105 | """ |
| 106 | from django.core.serializers.json import DjangoJSONEncoder |
| 107 | |
| 108 | json_str = json.dumps(value, cls=encoder or DjangoJSONEncoder).translate( |
| 109 | _json_script_escapes |
| 110 | ) |
| 111 | if element_id: |
| 112 | template = '<script id="{}" type="application/json">{}</script>' |
| 113 | args = (element_id, mark_safe(json_str)) |
| 114 | else: |
| 115 | template = '<script type="application/json">{}</script>' |
| 116 | args = (mark_safe(json_str),) |
| 117 | return format_html(template, *args) |
| 118 | |
| 119 | |
| 120 | def conditional_escape(text): |