collect() 函数为在 Twig 中构建数组提供了一个更友好的接口。Twig 作为一个视图层是有意保持极简主义的,并且构建一个数组需要一个持续的合并过程。
请看以下示例,了解如何使用原生 Twig |merge 过滤器构建数组:
{% set array = [] %}
{% for item in items %}
{% set array = array|merge([{ title: item.title, ... }]) %}
{% endfor %}使用 collect() 函数会返回 一个集合对象,让你转而推送元素。上述示例可以使用 push 方法实现。
{% set array = collect() %}
{% for item in items %}
{% do array.push({ title: item.title, ... }) %}
{% endfor %}将数组作为第一个参数传递,将会使用预填充的项初始化集合。
{% set array = collect([
{ title: item.title, ... },
{ title: item.title, ... }
]) %}该 shuffle() 方法将集合打乱。
{{ collect(songs).shuffle() }}在 foreach 循环中。
{% for fruit in collect(['apple', 'banana', 'orange']).shuffle() %}
{{ fruit }}
{% endfor %}该 sortBy() 和 sortByDesc 方法可以根据给定字段(键)对集合进行排序。
collect(data).sortBy('age')例如:
// Output: John David
{% set data = [{'name': 'David', 'age': 31}, {'name': 'John', 'age': 28}] %}
{% for item in collect(data).sortBy('age') %}
{{ item.name }}
{% endfor %}