在Django模板中切片一个列表

时间:2022-01-10 18:37:31

If I want to get first 5 elements from a list I would do mylist|slice:"5"

如果我想从一个列表中获得前5个元素,我要做mylist|切片:"5"

but I want a range, let say from 3 to 7. something like mylist[3:8] how would I do that in template

但我想要一个范围,从3到7。比如mylist[3:8]我如何在模板中那样做

2 个解决方案

#1


12  

you can just use

你可以使用

{{ mylist|slice:"3:8" }}

#2


9  

Its simple you will have to pass this in the slice filter then:

它很简单,你必须在切片过滤器中传递这个:

{{ mylist|slice:"3:8" }}

This filter takes care of all type of slicing you can perform on a list

这个过滤器负责处理可以在列表上执行的所有类型的切片

e.g. All this would work:

所有这一切都会起作用:

{{ mylist|slice:"3:8" }}

{{ mylist|slice:":2" }}

{{ mylist|slice:"3:" }}

{{ mylist|slice:":" }}

#1


12  

you can just use

你可以使用

{{ mylist|slice:"3:8" }}

#2


9  

Its simple you will have to pass this in the slice filter then:

它很简单,你必须在切片过滤器中传递这个:

{{ mylist|slice:"3:8" }}

This filter takes care of all type of slicing you can perform on a list

这个过滤器负责处理可以在列表上执行的所有类型的切片

e.g. All this would work:

所有这一切都会起作用:

{{ mylist|slice:"3:8" }}

{{ mylist|slice:":2" }}

{{ mylist|slice:"3:" }}

{{ mylist|slice:":" }}