Twig 按字段对对象数组进行排序 [英] Twig sort array of objects by field
本文介绍了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
这篇关于Twig 按字段对对象数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文