I'm using cycle to open and close a div for a row of content. It works great when there are more than a certain number of entries - in this case 4, but doesn't work when there are fewer than that. Is there a way to make this work so it always closes the div even if there are fewer entries than specified in the code?

{{ cycle(['<div class="row">', '', '', ''], loop.index0) | raw }}
... stuff....
{{ cycle(['', '', '', '</div>'], loop.index0) | raw }}

2 Answers 2


This is how I usually solve this problem, notice the explicit check for the last element in the list. You can set cols to whatever number of columns you want.

{% set cols = 4 %}
{% for thing in things %}
  {% if loop.index0 % cols == 0 %}
    <div class="row">
  {% endif %}
  {# other stuff #}
  {% if (loop.index0 % cols == cols - 1 or loop.last) %}
  {% endif %}
{% endfor %}

Maybe you can use Twig's batch for this?

Twig Batch

{% set items = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] %}
{% for row in items|batch(3, '') %}
<div class="row">
    {% for column in row %}
        <p>{{ column }}</p>
    {% endfor %}
{% endfor %}

Batch lets you have something to fall back on when you have less items. In this case there are 3 items within my row and if there will be 2, it will output what I have in the '', in this case nothing. (but I can put what I want in that '').

  • Nice! Just when you think you have a good handle on all the cool stuff Twig does, you forget there's batch... Commented Apr 21, 2017 at 18:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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