Numeric for loop in Django templates

ID : 10142

viewed : 34

Tags : djangodjango-templatesdjango

Top 5 Answer for Numeric for loop in Django templates

vote vote

91

I've used a simple technique that works nicely for small cases with no special tags and no additional context. Sometimes this comes in handy

{% for i in '0123456789'|make_list %}     {{ forloop.counter }} {% endfor %} 
vote vote

81

{% with ''|center:n as range %} {% for _ in range %}     {{ forloop.counter }} {% endfor %} {% endwith %} 
vote vote

76

Unfortunately, that's not supported in the Django template language. There are a couple of suggestions, but they seem a little complex. I would just put a variable in the context:

... render_to_response('foo.html', {..., 'range': range(10), ...}, ...) ... 

and in the template:

{% for i in range %}      ... {% endfor %} 
vote vote

70

My take on this issue, i think is the most pythonic. Create a my_filters.py in your apps templatetags directory.

@register.filter(name='times')  def times(number):     return range(number) 

Usage in your template:

{% load my_filters %} {% for i in 15|times %}     <li>Item</li> {% endfor %} 
vote vote

51

You can pass a binding of

{'n' : range(n) } 

to the template, then do

{% for i in n %} ... {% endfor %} 

Note that you'll get 0-based behavior (0, 1, ... n-1).

(Updated for Python3 compatibility)

Top 3 video Explaining Numeric for loop in Django templates

Related QUESTION?