Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top