简体   繁体   English

遍历数组内有限数量的元素

[英]Looping through a limited number of elements inside an array

I have an array of users, how can I make a limited number of iterations using twig. 我有大量的用户,如何使用twig进行有限数量的迭代。

I have 5 elements inside the array, and i only need to loop through 4 of them. 我在数组中有5个元素,我只需要遍历其中的4个元素。

instead of doing like this: 而不是像这样:

 for user in users 
     user 
 endfor 

it would be something like this 就像这样

 for ... in 0..3 
      user 
 endfor 

You can use the slice filter 您可以使用切片过滤器

{% for user in users|slice(0,4) %}
...
{% endfor %}

You can even use the twig shortcut 您甚至可以使用树枝快捷方式

{% for user in users[0:4] %}
...
{% endfor %}

You can use Twig extension Slice 您可以使用Twig扩展

In example : 例如:

{% for user in users|slice(0, -1) %} 
    ...
{% endfor %}

slice(0, -1) means you start from 0 and end to last element - 1 slice(0, -1)表示您从0开始到最后一个元素-1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM