Skip to content

Instantly share code, notes, and snippets.

@parrotmac
Created December 14, 2023 18:44
Show Gist options
  • Save parrotmac/b1736b205fb2f22d8cb7b931bd291ea9 to your computer and use it in GitHub Desktop.
Save parrotmac/b1736b205fb2f22d8cb7b931bd291ea9 to your computer and use it in GitHub Desktop.
Specialized Django `json_script` template tag for more complex data types.
import dataclasses
from django import template
from django.utils import html
from django.utils.safestring import mark_safe
from rest_framework.renderers import JSONRenderer
from rest_framework.utils import encoders
register = template.Library()
class JSONEncoder(encoders.JSONEncoder):
def default(self, obj):
if dataclasses.is_dataclass(obj):
return dataclasses.asdict(obj)
return super().default(obj)
@register.filter()
def advanced_json_script(data, element_id):
"""
Based on: django.utils.html.json_script
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.
"""
renderer = JSONRenderer()
renderer.encoder_class = JSONEncoder
json_str = renderer.render(data).decode("utf-8")
return html.format_html(
'<script id="{}" type="application/json">{}</script>',
element_id,
mark_safe(json_str),
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment