Commits

João Pedro Francese committed 7884378

[v0.2.16] Added as_json templatetag

Comments (0)

Files changed (2)

inoa/templatetags/as_json.py

+# -*- coding: utf-8 -*-
+from django.template import Library
+from django.template.defaultfilters import escapejs
+from django.utils.safestring import mark_safe
+from inoa.utils.json import ExtendedJSONEncoder
+import json
+
+
+register = Library()
+
+@register.filter
+def as_json(value):
+    """
+    Encodes a variable as JSON, escapes and and wraps it with quotes and javascript-decode.
+    The variable must be serializable with simplejson.
+    Usage (in a JavaScript section of a template):
+    var something = {{something|as_json}};
+    """
+    j = json.dumps(value, cls=ExtendedJSONEncoder)
+    j = escapejs(j)
+    j = 'jQuery.parseJSON("%s")' % j
+    return mark_safe(j)
 
 setup(
     name='django-inoa',
-    version='0.2.15',
+    version='0.2.16',
     author='Inoa',
     author_email='django@inoa.com.br',
     packages=packages,