Twig sort array of objects by field

后端 未结 8 2123
感动是毒
感动是毒 2020-12-17 09:31

I have entity with fields:

User

  • name
  • lastname
  • age

and few more. Im sending to Twig array with objec

8条回答
  •  别那么骄傲
    2020-12-17 09:43

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

提交回复
热议问题