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 %}