sort
sort
过滤器对序列和映射进行排序
1 2 3
{% for user in users|sort %}
...
{% endfor %}
注意
在内部,Twig 使用 PHP 的 asort 函数来维护索引关联。它通过将 Traversable 对象转换为数组来支持它们。
您可以传递一个箭头函数来配置排序
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
: 一个箭头函数