Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig Loop Grouping

Tags:

group-by

twig

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.

like image 378
azzy81 Avatar asked Apr 22 '26 12:04

azzy81


1 Answers

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 %}
like image 110
Damian Polac Avatar answered Apr 29 '26 07:04

Damian Polac