Created
February 8, 2012 20:47
-
-
Save silent1mezzo/1773608 to your computer and use it in GitHub Desktop.
Django {% set %} templatetag
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
class SetVarNode(template.Node): | |
def __init__(self, var_name, var_value): | |
self.var_name = var_name | |
self.var_value = var_value | |
def render(self, context): | |
try: | |
value = template.Variable(self.var_value).resolve(context) | |
except template.VariableDoesNotExist: | |
value = "" | |
context[self.var_name] = value | |
return u"" | |
def set_var(parser, token): | |
""" | |
{% set <var_name> = <var_value> %} | |
""" | |
parts = token.split_contents() | |
if len(parts) < 4: | |
raise template.TemplateSyntaxError("'set' tag must be of the form: {% set <var_name> = <var_value> %}") | |
return SetVarNode(parts[1], parts[3]) | |
register.tag('set', set_var) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment