Create new variables in templates

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from django import template

class AssignNode(template.Node):
    def __init__(self, name, value):
        self.name = name
        self.value = value
        
    def render(self, context):
        context[self.name] = self.value.resolve(context, True)
        return ''

def do_assign(parser, token):
    """
    Assign an expression to a variable in the current context.
    
    Syntax::
        {% assign [name] [value] %}
    Example::
        {% assign list entry.get_related %}
        
    """
    bits = token.contents.split()
    if len(bits) != 3:
        raise template.TemplateSyntaxError("'%s' tag takes two arguments" % bits[0])
    value = parser.compile_filter(bits[2])
    return AssignNode(bits[1], value)

register = template.Library()
register.tag('assign', do_assign)

More like this

  1. Counter model - run multiple persistent counters by simon 4 years, 10 months ago
  2. Filter change list by a date range by aruseni 2 years, 2 months ago
  3. logging to shell on dev server by chachan 1 year, 9 months ago
  4. IfValueTag by adurdin 7 years, 1 month ago
  5. Sphinx Search ORM by zeeg 6 years, 11 months ago

Comments

fivethreeo (on February 6, 2008):

A bug, forgot a template.Variable in there ?

#

chodorowicz (on January 29, 2011):

This is really useful, but it breaks if you use string with spaces as as the value - {% assign str "an string" %} produces: 'assign' tag takes two arguments

Exchanging token.contents.split() to token.split_contents() solves the problem

#

(Forgotten your password?)