views:

2773

answers:

6

How do I write a numeric for loop in a Django template? I mean something like

for i = 1 to n
+1  A: 

You don't pass n itself, but rather range(n) [the list of integers from 0 to n-1 included], from your view to your template, and in the latter you do {% for i in therange %} (if you absolutely insist on 1-based rather than the normal 0-based index you can use forloop.counter in the loop's body;-).

Alex Martelli
A: 

You can pass a binding of

{'n' : xrange(n) }

to the template, then do

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

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

Dave W. Smith
+4  A: 

Take a look at these template filters and tags, either of which is easy enough to include in your application.

The advantage of these compared to the other solutions (passing in a range of numbers) is that, once installed, these will always be available to your templates and template authors, without having to explicitly pass a valid range through your view code.

ars
ThanxThe former looks better to me
Lev
how does one include snippets into an application?
Fahim Akhter
+4  A: 

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 %}
tghw
+2  A: 

Just incase anyone else comes across this question… I've created a template tag which lets you create a range(...): http://www.djangosnippets.org/snippets/1926/

Accepts the same arguments as the 'range' builtin and creates a list containing
the result of 'range'.

Syntax:
    {% mkrange [start,] stop[, step] as context_name %}

For example:
    {% mkrange 5 10 2 as some_range %}
    {% for i in some_range %}
      {{ i }}: Something I want to repeat\n
    {% endfor %}

Produces:
    5: Something I want to repeat 
    7: Something I want to repeat 
    9: Something I want to repeat

David Wolever
A: 

Check out http://djangosnippets.org/snippets/2147/

variable/filter support for range values. Based on wolever's snippet.

berserkpi