Created
November 16, 2013 12:53
-
-
Save reebalazs/7499867 to your computer and use it in GitHub Desktop.
Json expression type for Chameleon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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