Twig 按字段对对象数组进行排序

问题描述:

我有带有字段的实体:

用户

  • 姓名
  • 姓氏
  • 年龄

还有更多.我使用对象用户发送到 Twig 数组.

and few more. Im sending to Twig array with objects user.

在表格中显示用户:

 {% for user in users %}
     <td>{{ user.name }}<td> <td>{{ user.lastname}}<td> <td>{{ user.age}}<td>
 {% endfor %}

如何在 Twig 中通过姓名或姓氏等对用户进行排序.我想创建可排序的表格.

How can I sort users via name or lastname etc. in Twig. I want to create sortable table.

从 Twig 2.12(2019 年 10 月 5 日发布)开始,您可以使用 sort 过滤器和 中的箭头函数>arrow 参数.

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 user in users|sort((a, b) => a.name <=> b.name) %}
    <td>{{ user.name }}</td> <td>{{ user.lastname}}</td> <td>{{ user.age}}</td>
{% endfor %}

Twig 文档:https://twig.symfony.com/doc/2.x/filters/sort.html