Sorting in the template, in Symfony2: using Twig to sort a collection of objects by property

24,496

Solution 1

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

Solution 2

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

Share:
24,496
Dieter
Author by

Dieter

Updated on November 06, 2020

Comments

  • Dieter
    Dieter over 3 years

    In a Symfony2 project I have a controller that retrieves a number of incidents from the database. These incidents have properties like start_time, stop_time, type, etc.

    In my view, I want to show these incidents in a table, sorted by start_time. I use Twig for my templating.

    I can pre-sort in my controller before passing it to the Twig template, but imho the controller shouldn't care that the view wants it sorted. Maybe another template that I create will want it sorted by type, for example.

    Now, is there a way that I can give the collection of incident-objects as-is to the Twig template, and have it sort it for me on the spot? Maybe with a '| sort' filter, but then with something like a '| property(start_time)' filter in front of it, if you know what I mean :-)

    Any advice is welcome, thanks in advance!

    Dieter

  • Dieter
    Dieter over 12 years
    That's what I needed to know. Thanks for the tip on the extension!
  • Dieter
    Dieter over 7 years
    I can't try it out myself anymore, but this does seem like exactly what I needed back then. Will mark this as the answer from now on. Thanks to both you and @futurecat!
  • Sanne
    Sanne over 2 years
    Do you still have the twig extension link? The link isnt working sadly :(