Login

Duplicating Template Tag

Author:
skarphace
Posted:
September 9, 2011
Language:
Python
Version:
1.3
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. Month / Year SelectDateWidget based on django SelectDateWidget by pierreben 3 months ago
  2. Python Django CRUD Example Tutorial by tuts_station 3 months, 2 weeks ago
  3. Browser-native date input field by kytta 5 months ago
  4. Generate and render HTML Table by LLyaudet 5 months, 1 week ago
  5. My firs Snippets by GutemaG 5 months, 2 weeks ago

Comments

Please login first before commenting.