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. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

Please login first before commenting.