Twig for loop puts every 2 elements in a new container

I have this loop:

{% for div in myHandleHere %} <div> {{ block.text }} </div> {% endfor %} 

This really outputs something like:

 <div> one </div> <div> two </div> <div> three </div> <div> ... </div> 

I want every 2 div to put them in a new container, for example:

 <div class="container"> <div> one </div> <div> two </div> </div> <div class="container"> <div> three </div> <div> ... </div> </div> 

Please, help

+7
html for-loop twig
source share
2 answers

The best solution in this case is to use a large batch filter , which allows you to process elements in groups:

 {% for pair in myHandleHere|batch(2) %} <div class="container"> {% for element in pair %} <div>{{ element }}</div> {% endfor %} </div> {% endfor %} 
+7
source share

What you want to do is either calculate which line you are on, or have a nested loop. Conveniently Twig has a couple of built -in loop variables that we can use.

Something like that:

 {% for div in myHandleHere %} {% if loop.index is odd %} <div class="container"> {% endif %} <div> {{ block.text }} </div> {% if loop.index is even or loop.last %} </div> {% endif %} {% endfor %} 

Scroll through all the blocks. At each iteration, if the loop counter is odd, i.e. Blocks 1, 3, 5, etc., Run the new <div class="container"> .

And if the cycle counter is even, i.e. blocks 2, 4, 6, etc., close this </div> .

Also, if you are in the last block, make sure that you also close the parent div, for example. in case you have an odd number of blocks, you want to output HTML as:

 <div class="container"> <div> one </div> <div> two </div> </div> <div class="container"> <div> three </div> <div> four </div> </div> <div class="container"> <div> five</div> </div> 
+2
source share

All Articles