提示如何从数组中获取第一个项

时间:2022-09-17 13:32:14

I need to get the first item from the field in the twig template. Is there some kind of function?

我需要从twig模板中的字段中获取第一个项。有什么功能吗?

3 个解决方案

#1


67  

Yes, there is, it is called first. The rest is copied from the documentation.

是的,有,它叫第一。其余部分是从文档中复制的。

New in version 1.12.2: The first filter was added in Twig 1.12.2.

新版本1.12.2:第一个过滤器添加在Twig 1.12.2中。

The first filter returns the first "element" of a sequence, a mapping, or a string:

第一个过滤器返回序列、映射或字符串的第一个“元素”:

{{ [1, 2, 3, 4]|first }}
{# outputs 1 #}

{{ { a: 1, b: 2, c: 3, d: 4 }|first }}
{# outputs 1 #}

{{ '1234'|first }}
{# outputs 1 #}

It also works with objects implementing the Traversable interface.

它还与实现可遍历接口的对象一起工作。

#2


3  

I was looking to get the last element of an array with twig and found this question and found out Twig has a last as well.

我在寻找一个带有twig的数组的最后一个元素,找到了这个问题,发现twig也有最后一个元素。

#3


0  

At Twig documentation: http://twig.sensiolabs.org/doc/filters/first.html, you can find the better answer and other related thing also.

在Twig文档:http://twig.sensiolabs.org/doc/filters/first.html,您可以找到更好的答案和其他相关的东西。

#1


67  

Yes, there is, it is called first. The rest is copied from the documentation.

是的,有,它叫第一。其余部分是从文档中复制的。

New in version 1.12.2: The first filter was added in Twig 1.12.2.

新版本1.12.2:第一个过滤器添加在Twig 1.12.2中。

The first filter returns the first "element" of a sequence, a mapping, or a string:

第一个过滤器返回序列、映射或字符串的第一个“元素”:

{{ [1, 2, 3, 4]|first }}
{# outputs 1 #}

{{ { a: 1, b: 2, c: 3, d: 4 }|first }}
{# outputs 1 #}

{{ '1234'|first }}
{# outputs 1 #}

It also works with objects implementing the Traversable interface.

它还与实现可遍历接口的对象一起工作。

#2


3  

I was looking to get the last element of an array with twig and found this question and found out Twig has a last as well.

我在寻找一个带有twig的数组的最后一个元素,找到了这个问题,发现twig也有最后一个元素。

#3


0  

At Twig documentation: http://twig.sensiolabs.org/doc/filters/first.html, you can find the better answer and other related thing also.

在Twig文档:http://twig.sensiolabs.org/doc/filters/first.html,您可以找到更好的答案和其他相关的东西。