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

doniyor
  • 36,596
  • 57
  • 175
  • 260

1 Answers1

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.

Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • 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? – doniyor Sep 03 '13 at 22:13
  • 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! – Brendan Oct 16 '14 at 15:04