Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

group by - Twig Loop Grouping

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 %}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...