How to evenly display data in 3 column lists using Twig?

I have an array containing cities, and I would like to place them in a list of 3 columns. How can I convert an array of cities dividing them into 3 column lists?

My html list:

<div class="col-md-4"> <ul> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> ... </ul> </div> <div class="col-md-4"> <ul> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> ... </ul> </div> <div class="col-md-4"> <ul> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> <li class="city-item"><a href="#">City</a></li> ... </ul> </div> 

I expect the data to appear in this order

 city0 city3 city6 city1 city4 city7 city2 city5 

What is the best approach for rendering data?

+6
source share
1 answer

Update 1: I created Twig Fiddle to include suggestions in comments. http://twigfiddle.com/0h54xy

Update 2: If you have a newer version of Twig, it is better to use a batch filter. See http://twigfiddle.com/0h54xy/5 for an example.


The % module operator is very useful here.

The // operator in Twig will split the number and put it on, i.e. 20 // 3 == 2

Note that Twig loop.index not indexed by zero, the first value is 1.

 {% if cities|length %} {% set citiesPerColumn = (cities|length / 3)|round(0, 'ceil') %} {% for city in cities %} {% if citiesPerColumn == 1 or loop.index % citiesPerColumn == 1 %} <div class="col-md-4"> <ul> {% endif %} <li class="city-item"><a href="#">{{ city }}</a></li> {% if loop.last or loop.index % citiesPerColumn == 0 %} </ul> </div> {% endif %} {% endfor %} {% endif %} 
+11
source

Source: https://habr.com/ru/post/957641/


All Articles