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


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 "a string" as my_var %}

Update (solved):

class DefineNode(Node):
    def __init__(self, var, name):
        self.var = var = name

    def __repr__(self):
        return "<DefineNode>"

    def render(self, context):
        context[] = self.var
        return ''

def define(parser, token):
    Adds a name to the context for referencing an arbitrarily defined string.

    For example:

        {% define "my_string" as my_string %}

    Now anywhere in the template:

        {{ my_string }}
    bits = list(token.split_contents())
    if (len(bits) != 4 or bits[2] != "as") or \
        not (bits[1][0] in ('"', "'") and bits[1][-1] == bits[1][0]):
        raise TemplateSyntaxError("%r expected format is '\"string\" as name'" % bits[0])
        value = bits[1][1:-1]
    name = bits[3]
    return DefineNode(value, name)


You don’t need to write your own tag. The built-in {% with %} tag does this.

Answered By – Daniel Roseman

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published