Login

Repeat Tag

Author:
daniellindsley
Posted:
May 9, 2009
Language:
HTML/template
Version:
Not specified
Tags:
templatetag repeat
Score:
1 (after 1 ratings)

License: BSD

Allows you to repeat a block of content a certain number of times.

 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
31
32
33
34
35
36
37
38
39
40
from django import template

register = template.Library()


class RepeatNode(template.Node):
    def __init__(self, nodelist, count):
        self.nodelist = nodelist
        self.count = template.Variable(count)
    
    def render(self, context):
        output = self.nodelist.render(context)
        return output * int(self.count.resolve(context))


def repeat(parser, token):
    """
    Repeats the containing text a certain number of times.
    
    Requires a single argument, an integer, to indicate the number of times to
    repeat the enclosing content.
    
    Example::
    
        {% repeat 3 %}foo{% endrepeat %}
    
    Yields::
    
        foofoofoo
    """
    bits = token.split_contents()
    
    if len(bits) != 2:
        raise template.TemplateSyntaxError('%r tag requires 1 argument.' % bits[0])
    
    count = bits[1]
    nodelist = parser.parse(('endrepeat',))
    parser.delete_first_token()
    return RepeatNode(nodelist, count)
repeat = register.tag(repeat)

More like this

  1. Template range tag by newmaniese 6 years, 12 months ago
  2. Repeat blocks with new context / simple Jinja-like macro system by miracle2k 7 years, 10 months ago
  3. Transparent encryption for model fields by shadfc 6 years, 11 months ago
  4. Overwriting file storage by rbanffy 4 years, 12 months ago
  5. change a widget attribute in ModelForm without define the field by jedie 6 years, 10 months ago

Comments

showell (on May 12, 2009):

This is nice, and I like how the integer can be a variable; it doesn't always have to be a literal as shown in the docstring.

#

Please login first before commenting.