from django.template.base import Node
from django.template.library import Library
register = Library()
class SpacelessJsonNode(Node):
def __init__(self, nodelist):
self.nodelist = nodelist
def render(self, context):
import json, unicodedata
content = self.nodelist.render(context).strip()
content = unicodedata.normalize('NFKD', content)
json_data = json.loads(content)
return safestring.mark_safe(json.dumps(json_data, ensure_ascii=False))
@register.tag(name='spaceless_json')
def spaceless_json(parser, token):
"""
Remove whitespace inside json-data.
Example usage::
This example returns this string::
"""
nodelist = parser.parse(('endspaceless_json',))
parser.delete_first_token()
return SpacelessJsonNode(nodelist)