Twig

灵活、快速且安全的
PHP 模板引擎

a Symfony Product
您正在阅读 Twig 3.x 的文档。切换到 Twig 1.x, 2.x 的文档。

问题与反馈

许可协议

Twig 文档 基于新 BSD 许可协议 授权。

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: 一个箭头函数