5

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

4

1 回答 1

7

如何使用内置切片过滤器:

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

如果你需要创建一个数字循环(就像 python 的range),你需要一个自定义模板标签,像这样:http ://djangosnippets.org/snippets/1926/

查看其他range片段:

另见:

顺便说一句,这听起来不像是模板的工作——考虑从视图中传递一个范围。而且,仅供参考,有人提议制作这样的标签,但它被拒绝了,因为it is trying to lead to programming in the template.- 考虑一下。

于 2013-09-03T22:11:14.033 回答