How do I write a numeric for
loop in a Django template? I mean something like
for i = 1 to n
This method supports all the functionality of the standard range([start,] stop[, step])
function
from django import template
register = template.Library()
@register.filter(name='range')
def _range(_min, args=None):
_max, _step = None, None
if args:
if not isinstance(args, int):
_max, _step = map(int, args.split(','))
else:
_max = args
args = filter(None, (_min, _max, _step))
return range(*args)
Usage:
{% load range %}
stop 5
{% for value in 5|range %}
{{ value }}
{% endfor %}
start 5 stop 10
{% for value in 5|range:10 %}
{{ value }}
{% endfor %}
start 5 stop 10 step 2
{% for value in 5|range:"10,2" %}
{{ value }}
{% endfor %}
Output
stop 5
0 1 2 3 4
start 5 stop 10
5 6 7 8 9
start 5 stop 10 step 2
5 7 9