Login

Duplicating Template Tag

Author:
skarphace
Posted:
September 9, 2011
Language:
Python
Version:
1.3
Tags:
template-tag duplicate loop
Score:
0 (after 0 ratings)

This template tag will duplicate its contents according to a variable or integer supplied to it.

{% duplicate 3 %}a{% endduplicate %}

This would return:

aaa

 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
30
from django import template
register = template.Library()

@register.tag
def duplicate(parser, token):
    nodelist = parser.parse(('endduplicate',))
    parser.delete_first_token()
    
    try:
        tag_name, repeat = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires exactly one arguments" % token.contents.split()[0])
    return DuplicateNode(nodelist, repeat)

class DuplicateNode(template.Node):
    def __init__(self, nodelist, repeat):
        self.nodelist = nodelist
        self.repeat = repeat
    def render(self, context):
        try:
            repeat = int(self.repeat)
        except ValueError:
            self.repeat = template.Variable(self.repeat)
            repeat = self.repeat.resolve(context)
        output = ''
        i = 0
        while i < repeat:
            output = output + self.nodelist.render(context)
            i = i + 1
        return output

More like this

  1. Wiki-like markup for sub templates by luckystarr 7 years, 8 months ago
  2. {% renderonce %} template tag by corrr 4 years, 11 months ago
  3. Template tag: Extend with parameters by miracle2k 7 years, 7 months ago
  4. View Permission Decorator Helper by jgeewax 6 years, 10 months ago
  5. Currency filter by kljensen 7 years, 4 months ago

Comments

Please login first before commenting.