I have this loop:
{% for div in myHandleHere %}
<div> {{ block.text }} </div>
{% endfor %}
That actually outputs something like:
<div> one </div>
<div> two </div>
<div> three </div>
<div> ... </div>
What I want is, every 2 div, put them in a new container, like:
<div class="container">
<div> one </div>
<div> two </div>
</div>
<div class="container">
<div> three </div>
<div> ... </div>
</div>
Please help
The best solution in this case is to use the great batch filter which allows to process elements in groups:
{% for pair in myHandleHere|batch(2) %}
<div class="container">
{% for element in pair %}
<div>{{ element }}</div>
{% endfor %}
</div>
{% endfor %}
What you want to do is either keep a count of which row you're on, or have a nested loop. Conveniently Twig has a couple of built-in loop variables we can use.
Something like this:
{% 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 %}
Loop over all your blocks. On each iteration, if the loop counter is odd, i.e. blocks 1, 3, 5 etc, start a new <div class="container">
.
And if the loop counter is even, i.e. blocks 2, 4, 6 etc, close that </div>
.
Also if you're on the last block, make sure and close the parent div too, e.g. in case you only have an odd number of blocks, you want to output HTML like:
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With