Sorting in the template, in Symfony2: using Twig to sort a collection of objects by property
There is no way to sort an array by a property with Twig. You still have the sort
filter (described here: http://twig.sensiolabs.org/doc/filters/sort.html) but it will just sort your array like php will do with the sort
function.
What you can do is create a TwigExtension and implement your own filter. It's very easy and very well documented here: http://twig.sensiolabs.org/doc/advanced.html
futurecat is totally right: there's no way to do this out-of-the-box. Even if his answer has been accepted, I'm adding this for completeness:
You can use snilius/twig-sort-by-field Twig extension, which will provide the filter you need.
Install it using composer require snilius/twig-sort-by-field
, and enjoy its sortbyfield
filter:
{% for item in base | sortbyfield('name') %} {{ item.name }}{% endfor %}