Twig extension to sort of entities by DateTime property

If one wants to sort a collection of doctrine in the template after a time stamp (createdAt the example), before actually make this.

If this is not possible, e.g.. in the Sonata Admin Bundle, then you can use this twig extension:

{% foo| sortByCreatedAt('asc') %}

Twig extension code:


namespace App\Twig;

use App\Entity\Tag;
use Doctrine\ORM\PersistentCollection;
use Twig\Extension\AbstractExtension;
use Twig\TwigFilter;

class AppExtension extends AbstractExtension
    public function getFilters()
        return array(
            new TwigFilter('sortByCreatedAt', array($this, 'sortByCreatedAt')),

     * @param PersistentCollection $objects
     * @return mixed
    public function sortByCreatedAt($objects, $direction = 'asc')
        $objects = $objects->toArray();
        usort($objects, function ($a, $b) use($direction) {
            if ($direction === 'asc') {
                return $a->getCreatedAt() >  $b->getCreatedAt();
            } elseif ($direction === 'desc') {
                return $a->getCreatedAt() <  $b->getCreatedAt();
            } else {
                throw new \Exception('unknown sort direction');

        return $objects;