Is there a Django template tag that lets me set a context variable?
- by hekevintran
I want to be able to set variables in a template to string values. I wrote a tag, but it doesn't seem to change the context. The intended use is:
{% define my_var as "a string" %}
class DefineNode(Node):
def __init__(self, value, variable_name, nodelist):
self.value = value
self.variable_name = variable_name
self.nodelist = nodelist
def __repr__(self):
return "<DefineNode>"
def render(self, context):
context[self.variable_name] = self.value
return ''
@register.tag
def define(parser, token):
bits = list(token.split_contents())
if len(bits) != 4:
raise TemplateSyntaxError("%r expected format is 'value as variable'" % bits[0])
if bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]:
value = bits[1][1:-1]
nodelist = parser.parse(('enddefine',))
parser.delete_first_token()
return DefineNode(value, bits[3], nodelist)
I