I have array contains cities and I would like to put them on the 3 column list. How can I render an array of cities spliting them equally into 3 column list?
My html lis
Update 1: I have created a Twig Fiddle to incorporate suggestions in the comments. http://twigfiddle.com/0h54xy
Update 2: If you have a newer version of Twig, it might be better to use the batch filter. See http://twigfiddle.com/0h54xy/5 for an example.
This is where the modulus operator %
is very useful.
The //
operator in Twig will divide a number and floor it, i.e. 20 // 3 == 2
Note that Twig's loop.index
is not zero-indexed, 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 %}
{% endif %}
- {{ city }}
{% if loop.last or loop.index % citiesPerColumn == 0 %}
{% endif %}
{% endfor %}
{% endif %}