Skip to content

Instantly share code, notes, and snippets.

@andreyvit
Created February 24, 2009 20:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andreyvit/69760 to your computer and use it in GitHub Desktop.
Save andreyvit/69760 to your computer and use it in GitHub Desktop.
@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