Login

Template range filter

Author:
zalun
Posted:
March 9, 2009
Language:
HTML/template
Version:
Not specified
Tags:
template filter range
Score:
6 (after 7 ratings)

Easy to use range filter. Just in case you have to use a "clean" for loop in the template.

Inspired by Template range tag

Copy the file to your templatetags and load them.

Django doc | Custom template tags and filters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from django.template import Library

register = Library()

@register.filter
def get_range( value ):
  """
    Filter - returns a list containing range made from given value
    Usage (in template):

    <ul>{% for i in 3|get_range %}
      <li>{{ i }}. Do something</li>
    {% endfor %}</ul>

    Results with the HTML:
    <ul>
      <li>0. Do something</li>
      <li>1. Do something</li>
      <li>2. Do something</li>
    </ul>

    Instead of 3 one may use the variable set in the views
  """
  return range( value )

More like this

  1. mkrange - create a range() inside a template - variable/filter support for range values by berserkpi 6 years ago
  2. range tag by marco.fucci 7 years, 3 months ago
  3. Past days template filter by ramen 6 years, 9 months ago
  4. isoutc template filter by japerk 7 years, 4 months ago
  5. Time ranges like 7-9 p.m. by sgb 8 years, 7 months ago

Comments

pro547 (on May 2, 2009):
<p>This should be a default filter</p>

#

marcalj (on July 28, 2009):
<p>@pro547 I second that!</p> <p>Thanks for the snippet! :)</p>

#

jerry2801 (on October 20, 2009):
<p>simple and great!</p>

#

rizumu (on October 19, 2010):
<p>for one based, you can add 1 via a list comprehension</p> <pre>return [v + 1 for v in range(value)] </pre>

#

alanhussey (on January 9, 2013):
<p>Would it make more sense to call this as_range instead of get_range? </p>

#

ara (on February 1, 2014):
<p>This doesnt work tho:</p> <pre> {% for x in 3|get_range %} <tr> <td></td> <td></td> <td></td> </tr> {% endfor %} </pre> <p>But this works fine:</p> <pre> {% for x in 3|get_range %} <tr> <td{{ x }}></td> <td></td> <td></td> </tr> {% endfor %} </pre>

#

Please login first before commenting.