Matthias Andreas Benkard | 12a5735 | 2021-12-28 18:02:04 +0100 | [diff] [blame^] | 1 | ``sort`` |
| 2 | ======== |
| 3 | |
| 4 | The ``sort`` filter sorts an array: |
| 5 | |
| 6 | .. code-block:: twig |
| 7 | |
| 8 | {% for user in users|sort %} |
| 9 | ... |
| 10 | {% endfor %} |
| 11 | |
| 12 | .. note:: |
| 13 | |
| 14 | Internally, Twig uses the PHP `asort`_ function to maintain index |
| 15 | association. It supports Traversable objects by transforming |
| 16 | those to arrays. |
| 17 | |
| 18 | You can pass an arrow function to sort the array: |
| 19 | |
| 20 | .. code-block:: html+twig |
| 21 | |
| 22 | {% set fruits = [ |
| 23 | { name: 'Apples', quantity: 5 }, |
| 24 | { name: 'Oranges', quantity: 2 }, |
| 25 | { name: 'Grapes', quantity: 4 }, |
| 26 | ] %} |
| 27 | |
| 28 | {% for fruit in fruits|sort((a, b) => a.quantity <=> b.quantity)|column('name') %} |
| 29 | {{ fruit }} |
| 30 | {% endfor %} |
| 31 | |
| 32 | {# output in this order: Oranges, Grapes, Apples #} |
| 33 | |
| 34 | Note the usage of the `spaceship`_ operator to simplify the comparison. |
| 35 | |
| 36 | Arguments |
| 37 | --------- |
| 38 | |
| 39 | * ``arrow``: An arrow function |
| 40 | |
| 41 | .. _`asort`: https://secure.php.net/asort |
| 42 | .. _`spaceship`: https://www.php.net/manual/en/language.operators.comparison.php |