How do I write a numeric for
loop in a Django template? I mean something like
for i = 1 to n
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;-).
This essentially requires a range
function. A Django feature ticket was raised (https://code.djangoproject.com/ticket/13088) for this but closed as "won't fix" with the following comment.
My impression of this idea is that it is trying to lead to programming in the template. If you have a list of options that need to be rendered, they should be computed in the view, not in the template. If that's as simple as a range of values, then so be it.
They have a good point - Templates are supposed to be very simple representations of the view. You should create the limited required data in the view and pass to the template in the context.
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 %}
Maybe like this?
{% for i in "x"|rjust:"100" %}
...
{% endfor %}
For those who are looking to simple answer, just needing to display an amount of values, let say 3 from 100 posts for example just add {% for post in posts|slice:"3" %}
and loop it normally and only 3 posts will be added.
{% for i in range(10) %}
{{ i }}
{% endfor %}