小枝环分组 [英] Twig Loop Grouping

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

问题描述

  firstname |姓氏颜色
弗雷德史密斯蓝
詹姆斯福尔摩斯红
Sarah Fisher蓝
Chrstine Jenkins黄
Sid Wells红
Cory Simpson蓝
劳拉琼斯黄色

有了这些数据,我需要通过'color'列对它们进行分组。通过基于颜色在用户周围包裹一个div。例如

 < div class =colour_container> 
弗雷德史密斯 - 蓝色< br>
Sarah Fisher - 蓝色< br>
Cory Simpson - 蓝色< br>
< / div>

< div class =colour_container>
詹姆斯霍姆斯 - 红色< br>
Sid Wells - 红色< br>
< / div>

< div class =colour_container>
Christine Jenkins - 黄色< br>
劳拉琼斯 - 黄色< br>
< / div>

现在,如果我使用树枝循环,则会将div放在每个名称周围,而不是按颜色对它们进行分组。什么是获得上述输出最简单的方法?

  {%对于人物中的%} 
我在循环中尝试了各种各样的东西,但我很挣扎。 < div class =colour_container>
{{p.firstname}} {{p.surname}} - {{p.colour}}
< / div>
{%endfor%}

我需要它以某种方式先循环唯一的颜色值,然后循环访问属于该颜色的名称。

解决方案

我最近有类似的问题。我做了扩展,并将其作为开源发布。它引入了lambda表达式和 | group_by 过滤器。

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



有了这个,你可以简单地写:

  {color for color,group in people | group_by(=> _.colour)%} 
< ; div class =colour_container>
{对于群组中的人员%}
{{person.firstname}} {{person.surname}} - {{person.colour}}
{%endfor%}
< / div>
{%endfor%}


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天全站免登陆