Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig sort array of objects by field

Tags:

twig

I have entity with fields:

User

  • name
  • lastname
  • age

and few more. Im sending to Twig array with objects user.

In twig display users in table:

 {% for user in users %}
     <td>{{ user.name }}<td> <td>{{ user.lastname}}<td> <td>{{ user.age}}<td>
 {% endfor %}

How can I sort users via name or lastname etc. in Twig. I want to create sortable table.

like image 969
user3735229 Avatar asked Aug 08 '14 00:08

user3735229


3 Answers

Starting with Twig 2.12 (released on October 5, 2019) you can use the sort filter with an arrow function in the arrow argument.

For example, to order by name:

{% for user in users|sort((a, b) => a.name <=> b.name) %}
    <td>{{ user.name }}</td> <td>{{ user.lastname}}</td> <td>{{ user.age}}</td>
{% endfor %}

Twig docs: https://twig.symfony.com/doc/2.x/filters/sort.html

like image 185
cgaldiolo Avatar answered Nov 06 '22 18:11

cgaldiolo


Yes, You can add custom filter:

{% for user in users|usort %}
    ...
{% endfor %}

and then add Extension/new filter to Twig:

new \Twig_SimpleFilter('usort', array($this, 'usortFilter'))

public function usortFilter($item){
    usort($item, function ($item1, $item2) {
        if ($item1['orderNo'] == $item2['orderNo']) return 0;
        return $item1['orderNo'] < $item2['orderNo'] ? -1 : 1;
    });

    return $item;
}
like image 34
unbreak Avatar answered Nov 06 '22 18:11

unbreak


Sorting in reverse order:

{% for user in users|sort|reverse %}
    ...
{% endfor %}

sort and revers are combinable.

like image 5
BenS. Avatar answered Nov 06 '22 16:11

BenS.