Login

Repeat Tag

Author:
daniellindsley
Posted:
May 9, 2009
Language:
HTML/template
Version:
Not specified
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. Bootstrap Accordian by Netplay4 5 years, 3 months ago
  2. Bootstrap theme for django-endless-pagination? by se210 8 years, 3 months ago
  3. Bootstrap theme for django-endless-pagination? by se210 8 years, 3 months ago
  4. Reusable form template with generic view by roldandvg 8 years, 4 months ago
  5. Pagination Django with Boostrap by guilegarcia 8 years, 6 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.