lithiumlab lithiumlab - 1 month ago 8
Twig Question

A solution for grouping items in loop with Timber and Twig

Often i need to do some tricky layout on dynamic elements like galleries.
Here's one example:

<ul>
<li class="slide">
<img src="img_01.jpg">
<img src="img_02.jpg">
</li>
<li class="slide">
<img src="img_03.jpg">
<img src="img_04.jpg">
</li>
<li class="slide">
<img src="img_05.jpg">
<img src="img_06.jpg">
</li>
</ul>


I've managed to do it with the following snippet. But i wanted some suggestions if possible about how to make it more flexible or more simple, like grouping by any number. Maybe using cycle() or any other method. I was getting strange results using the slice() or array[1:2] notation.

<ul>
{% for image in gallery %}
{% set current = loop.index %}
{% set next = current + 1 %}
{% if current is odd %}
<li class="slide">
{% for image in gallery %}
{% if loop.index in [current,next] %}
{% set th = TimberImage(image) %}
<img src="{{th.src}}">
{% endif %}
{% endfor %}
</li>
{% endif %}
{% endfor %}
</ul>


Any suggestions are welcomed.
Timber becomes very handy for quick in and out fixes with Timber::compile or custom themes with full routing. The purpose of the question is to create some snippet that can be reused.

Kudos to creators.
https://github.com/timber/timber

Answer

You can approach with the rest of the division with the following code (Here a working solutions):

{# number of element for every section #}
{% set section = 2%}

<ul>
{% for image in gallery %}
   {% if loop.index % section == 1  %}
     <li class="slide">
   {% endif %}
   {% set th = TimberImage(image) %}
       <img src="{{th.src}}">
   {% if loop.index % section == 0 or loop.last %}
     </li>
  {% endif %}
{% endfor %}
</ul>

You can easily reuse this code making a Twig macro using as parameter the gallery and the number of element for section (highlighted with the variable section

Comments