Created
February 24, 2009 20:22
-
-
Save andreyvit/69760 to your computer and use it in GitHub Desktop.
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
@register.tag(name='e') | |
def parse_eval_tag(parser, token): | |
tag_name, code = token.contents.split(' ', 1) | |
return PythonEvalNode(code, escape=(lambda x:x)) | |
@register.tag(name='ee') | |
def parse_eval_and_escape_tag(parser, token): | |
tag_name, code = token.contents.split(' ', 1) | |
return PythonEvalNode(code, escape=escape) | |
@register.tag(name='set') | |
def parse_exec_tag(parser, token): | |
tag_name, variable, code = token.contents.split(' ', 2) | |
return PythonSetNode(variable, code) | |
class PythonEvalNode(templ.Node): | |
def __init__(self, code, escape): | |
self.code = code | |
self.escape = escape | |
def render(self, context): | |
try: | |
v = eval(self.code, globals(), context) | |
v = str(v) | |
return self.escape(v) | |
except Exception, e: | |
logging.error("""Python Eval Tag "%s" raised %s: %s """ % (self.code, e.__class__.__name__, e.message)) | |
return "" | |
class PythonSetNode(templ.Node): | |
def __init__(self, variable, code): | |
self.variable = variable | |
self.code = code | |
def render(self, context): | |
try: | |
v = eval(self.code, globals(), context) | |
context[self.variable] = v | |
except Exception, e: | |
logging.error("""Python Set Tag %s "%s" raised %s: %s """ % (self.variable, self.code, e.__class__.__name__, e.message)) | |
return "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment