Skip to content

Instantly share code, notes, and snippets.

@reebalazs
Created November 16, 2013 12:53
Show Gist options
  • Save reebalazs/7499867 to your computer and use it in GitHub Desktop.
Save reebalazs/7499867 to your computer and use it in GitHub Desktop.
Json expression type for Chameleon
import json
from chameleon.zpt.template import (
PageTemplate,
PageTemplateFile
)
from chameleon.tales import StructureExpr
from chameleon.utils import unicode_string
from chameleon.astutil import Symbol
class Json(object):
def __init__(self, value):
self.json_string = self.transform(value)
def __str__(self):
return unicode_string(self.json_string)
__html__ = __repr__ = __str__
@classmethod
def transform(cls, value):
return json.dumps(value) \
.replace('\u2028', r'\u2028') \
.replace('\u2029', r'\u2029') \
.replace('</', r'\u003c\u002f')
class JsonExpr(StructureExpr):
wrapper_class = Symbol(Json)
# extend Chameleon
PageTemplate.expression_types['json'] = JsonExpr
PageTemplateFile.expression_types['json'] = JsonExpr
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment