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)
Comments
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):
#
I liked it, but I wanted to have something simpler which would work with variables - I created Template range filter
#
i think """ http://www.djangosnippets.org/snippets/1357/ """ can replace this job~~ ^_^
#
I've created a template tag based on this which allows you to specify a 'start' and 'step', like the 'range' builtin: http://www.djangosnippets.org/snippets/1926/.
#
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.
#