Duplicating Template Tag

 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 6 years, 7 months ago
  2. {% renderonce %} template tag by corrr 3 years, 10 months ago
  3. Template tag: Extend with parameters by miracle2k 6 years, 6 months ago
  4. View Permission Decorator Helper by jgeewax 5 years, 9 months ago
  5. Currency filter by kljensen 6 years, 3 months ago

Comments

(Forgotten your password?)