I have entity with fields:
User
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.
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
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;
}
Sorting in reverse order:
{% for user in users|sort|reverse %}
...
{% endfor %}
sort and revers are combinable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With