Template tag to create a list from one or more variables and/or literals

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
@register.tag
def collect(parser, token):
    bits = list(token.split_contents())
    if len(bits) > 3 and bits[-2] == 'as':
        varname = bits[-1]
        items = bits[1:-2]
        return CollectNode(items, varname)
    else:
        raise template.TemplateSyntaxError('%r expected format is "item [item ...] as varname"' % bits[0])

class CollectNode(template.Node):
    def __init__(self, items, varname):
        self.items = map(template.Variable, items)
        self.varname = varname

    def render(self, context):
        context[self.varname] = [i.resolve(context) for i in self.items]
        return ''

More like this

  1. shuffle templatetag by deanmalmgren 2 years, 2 months ago
  2. PositionField by jpwatts 4 years, 10 months ago
  3. mkrange - create a range() inside a template by wolever 3 years, 3 months ago
  4. Pagination/Filtering Alphabetically by zain 4 years, 2 months ago
  5. YUI Loader as Django middleware by akaihola 5 years, 1 month ago

Comments

Tomek (on November 22, 2010):

It would be also nice to have possibility "collect" some value into tuple.

#

(Forgotten your password?)