在Symfony2中对模板进行排序:使用Twig按属性对对象集合进行排序 [英] Sorting in the template, in Symfony2: using Twig to sort a collection of objects by property

查看:93
本文介绍了在Symfony2中对模板进行排序:使用Twig按属性对对象集合进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Symfony2项目中,我有一个控制器,该控制器从数据库中检索许多事件.这些事件具有诸如start_time,stop_time,type等的属性.

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.

在我看来,我想在一个表中显示这些事件,并按start_time排序.我用Twig做模板.

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

我可以在将控制器传递到Twig模板之前对其进行预排序,但是恕我直言,控制器无需关心视图是否希望对其进行排序.例如,也许我创建的另一个模板希望按类型对它进行排序.

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.

现在,有没有办法我可以将事件对象的集合原样提供给Twig模板,并当场对它进行排序? 也许带有'|排序"过滤器,然后加上"|" property(start_time)'过滤器放在它前面,如果您知道我的意思:-)

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

推荐答案

futurecat是完全正确的:没有现成的方法可以做到.即使他的回答已被接受,我还是为了完整性而添加:

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:

您可以使用 snilius/twig-sort-by-field Twig扩展程序,它将提供您需要的过滤器.

You can use snilius/twig-sort-by-field Twig extension, which will provide the filter you need.

使用composer require snilius/twig-sort-by-field安装它,并享受其sortbyfield过滤器:

Install it using composer require snilius/twig-sort-by-field, and enjoy its sortbyfield filter:

{% for item in base | sortbyfield('name') %}
    {{ item.name }}
{% endfor %}

这篇关于在Symfony2中对模板进行排序:使用Twig按属性对对象集合进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆