sort

这个 sort 筛选器对数组排序:

1
2
3
{% for user in users|sort %}
    ...
{% endfor %}

注解

在内部,Twig使用PHP asort 函数来维护索引关联。它通过将可遍历对象转换为数组来支持这些对象。

您可以传递一个箭头函数来对数组进行排序:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{% set fruits = [
    { name: 'Apples', quantity: 5 },
    { name: 'Oranges', quantity: 2 },
    { name: 'Grapes', quantity: 4 },
] %}

{% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %}
    {{ fruit }}
{% endfor %}

{# output in this order: Oranges, Grapes, Apples #}

注意 spaceship 运算符来简化比较。

争论

  • arrow :箭头函数