Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

twig for loop put every 2 elements in a new container

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

like image 322
neoDev Avatar asked Jul 02 '15 11:07

neoDev


2 Answers

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 %}
like image 106
Javier Eguiluz Avatar answered Sep 22 '22 00:09

Javier Eguiluz


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>
like image 44
duncan Avatar answered Sep 22 '22 00:09

duncan