Is there a Django template tag that lets me set a context variable?

Posted by hekevintran on Stack Overflow See other posts from Stack Overflow or by hekevintran
Published on 2010-04-02T10:58:57Z Indexed on 2010/04/02 11:03 UTC
Read the original article Hit count: 425

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about django

Related posts about django-templates