树枝循环分组 [英] Twig Loop Grouping

查看:19
本文介绍了树枝循环分组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Lets say I have some data called 'people' in an array past into a twig template like this:

firstname | surname | colour
Fred        Smith     Blue
James       Holmes    Red
Sarah       Fisher    Blue
Chrstine    Jenkins   Yellow
Sid         Wells     Red
Cory        Simpson   Blue
Laura       Jones     Yellow

With this data i need to group them by the 'colour' column. by wrapping a div around the users based on there colour. e.g

<div class="colour_container">
Fred Smith - Blue<br>
Sarah Fisher - Blue<br>
Cory Simpson - Blue<br>
</div>

<div class="colour_container">
James Holmes - Red<br>
Sid Wells - Red<br>
</div> 

<div class="colour_container">
Christine Jenkins - Yellow<br>
Laura Jones - Yellow<br>
</div>

now if I use a twig loop, it puts the div around each name rather than grouping them by colour. Whats the easiest way to get the above output? Ive tried all sorts of things in the loop but I am struggling.

{% for p in people %}
   <div class="colour_container">
       {{ p.firstname }} {{ p.surname }} - {{ p.colour }}
   </div>
{% endfor %}

I need it to somehow loop through unique colour values first then loop through the names that belong to that colour.

解决方案

I've had similar problem recently. I have made extension and published it as open source. It introduces lambda expressions and |group_by filter.

https://github.com/dpolac/twig-lambda

With that you can simply write:

{% for colour, group in people|group_by(=> _.colour) %}
   <div class="colour_container">
       {% for person in group %}
           {{ person.firstname }} {{ person.surname }} - {{ person.colour }}
       {% endfor %}
   </div>
{% endfor %}

这篇关于树枝循环分组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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