Login

Template range tag

Author:
newmaniese
Posted:
June 1, 2008
Language:
Python
Version:
.96
Score:
1 (after 1 ratings)

This is a simple tag that I am sure has been written before, but it helps people with the problem, 'how do I iterate through a number in the tempaltes?'.

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

#

Please login first before commenting.