how to set custom forloop start point in django template
Asked Answered
S

1

6

There is a forloop in java where i can tell where to start and where to end:

for(int i=10;i<array.length;i++){

}

but how can i implement this int i=10 in django template? How can i set the starting and ending point on my own?

there is a forloop.first and forloop.last, but they are defined inside the loop and i cannot do something like this?:

{{forloop.first=10}}

{% for athlete in athlete_list %}
    <li>{{ athlete.name }}</li>
{% endfor %}

{{forloop.last=20}}

I read the django doc but this feature seems to be not there

Smarm answered 3/9, 2013 at 22:5 Comment(3)
Why do you need this?Infantryman
@thomasorozco, just out of interest.Smarm
u can build a custom template tag which can do that for you, something like this djangosnippets.org/snippets/779Colleague
I
8

How about using built-in slice filter:

{% for athlete in athlete_list|slice:"10:20" %}
    <li>{{ athlete.name }}</li>
{% endfor %}

If you need to make a numeric loop (just like python's range), you need a custom template tag, like this one: http://djangosnippets.org/snippets/1926/

See other range snippets:

Also see:

By the way, this doesn't sound like a job for templates - consider passing a range from the view. And, FYI, there was a proposal to make such tag, but it was rejected because it is trying to lead to programming in the template. - think about it.

Indo answered 3/9, 2013 at 22:11 Comment(2)
my example was just an example code and not really mine. but the real question is: can i count from 2001 till 3001 in template in forloop?Smarm
I have a loop where the first item was styled a certain way, and subsequent items were styled differently. Doing so wrecked divisibleby as a way of adding clearfixes in Bootstrap, but this enabled me to do what I wanted. Thanks for the answer!Heartburn

© 2022 - 2024 — McMap. All rights reserved.