4

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

8

I usually do this like so:

{% for block in blocks %}
  {% if loop.index0 % 2 == 0 %}
    <div>
  {% endif %}
   {# other stuff #}
  {% if loop.index0 % 2 == 1 or loop.last %}
    </div>
  {% endif %}
{% endfor %}

Or, more generally,

{% set cols = 2 %}
{% for block in blocks %}
  {% if loop.index0 % cols == 0 %}
    <div>
  {% endif %}
   {# other stuff #}
  {% if (loop.index0 % cols == cols - 1 or loop.last) %}
    </div>
  {% endif %}
{% endfor %}
| improve this answer | |
5

I think batch that @Alec Ritson mentioned is definitely the way to go.

However, here's another approach for fun.

You can use cycle.

{{ cycle('<div>', '') }}
  {{ foo }}
{{ cycle('</div>', '') }}

But let me repeat: I really think batch is the way to go.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.