Template range 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
31
32
33
34
35
36
37
38
39
40
from django.template import Library, Node, TemplateSyntaxError

register = Library()

class RangeNode(Node):
    def __init__(self, num, context_name):
        self.num, self.context_name = num, context_name
    def render(self, context):
        context[self.context_name] = range(int(self.num))
        return ""
        
@register.tag
def num_range(parser, token):
    """
    Takes a number and iterates and returns a range (list) that can be 
    iterated through in templates
    
    Syntax:
    {% num_range 5 as some_range %}
    
    {% for i in some_range %}
      {{ i }}: Something I want to repeat\n
    {% endfor %}
    
    Produces:
    0: Something I want to repeat 
    1: Something I want to repeat 
    2: Something I want to repeat 
    3: Something I want to repeat 
    4: Something I want to repeat
    """
    try:
        fnctn, num, trash, context_name = token.split_contents()
    except ValueError:
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    if not trash == 'as':
        raise TemplateSyntaxError, "%s takes the syntax %s number_to_iterate\
            as context_variable" % (fnctn, fnctn)
    return RangeNode(num, context_name)

More like this

  1. range tag by marco.fucci 4 years, 11 months ago
  2. mkrange - create a range() inside a template by wolever 4 years, 2 months ago
  3. Template range loop by nfg 4 years, 2 months ago
  4. Repeat Tag by daniellindsley 4 years, 11 months ago
  5. mkrange - create a range() inside a template - variable/filter support for range values by berserkpi 3 years, 8 months ago

Comments

Penrose (on March 3, 2009):

Great tag!

To be able call the tag with dynamic values instead of integer literals, the Variable class can be used (works with Django 1.0):

class RangeNode(Node):
    def __init__(self, num, context_name):
        self.num = Variable(num)
        self.context_name = context_name

    def render(self, context):
        context[self.context_name] = range(int(self.num.resolve(context)))
        return ""

#

Ztyx (on January 11, 2013):

Note that the created range can only be used once in Python 3. It will needl to be wrapped in a list() to be reused.

#

(Forgotten your password?)