Twig

The flexible, fast, and secure
template engine for PHP

a Symfony Product
Docs Filters sort
You are reading the documentation for Twig 3.x. Switch to the documentation for Twig 1.x. 2.x.

Questions & Feedback

License

Twig documentation is licensed under the new BSD license.

sort

The sort filter sorts sequences and mappings:

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

Note

Internally, Twig uses the PHP asort function to maintain index association. It supports Traversable objects by transforming those to arrays.

You can pass an arrow function to configure the sorting:

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

Note the usage of the spaceship operator to simplify the comparison.

Arguments

  • arrow: An arrow function