Login

spaceless_json

Author:
dkoldyaev
Posted:
March 4, 2019
Language:
Python
Version:
Not specified
Tags:
django templatetag json spaceless formatting application/id+json
Score:
1 (after 1 ratings)

Now you can format and compress json-data in django template

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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::
    
            <script type="application/id+json">
            {% spaceless_json %}
                {
                    "foo":  "bar",
    
                            "foo2":
                                    "bar2"
                }
            {% endspaceless_json %}
            </script>
    
        This example returns this string::
        
            <script type="application/id+json">{"foo":"bar", "foo2":"bar2"}</script>
        """
        nodelist = parser.parse(('endspaceless_json',))
        parser.delete_first_token()
        return SpacelessJsonNode(nodelist)

More like this

Comments

Please login first before commenting.