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. Add Toggle Switch Widget to Django Forms by OgliariNatan 2 months, 2 weeks ago
  2. get_object_or_none by azwdevops 6 months, 1 week ago
  3. Mask sensitive data from logger by agusmakmun 8 months ago
  4. Template tag - list punctuation for a list of items by shapiromatron 1 year, 10 months ago
  5. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 1 year, 10 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.