1

In Twig I require that each group of four results is wrapped inside a div.

This is the final html I want, each group of 4 items must be wrapped:

{% for item in items %}
<div class="wrapper">
  {{ item }}
  {{ item }}
  {{ item }}
  {{ item }}
</div>
<div class="wrapper">
  {{ item }}
  {{ item }}
  {{ item }}
  {{ item }}
</div>
{% endfor %}
Viktor
  • 2,623
  • 3
  • 19
  • 28
Ricardo Castañeda
  • 5,746
  • 6
  • 28
  • 41
  • I see you have an accepted answer, but also check out [`batch`](http://twig.sensiolabs.org/doc/filters/batch.html) that seems quite similar to `each_slice`. – Maerlyn Dec 11 '14 at 08:48
  • @Maerlyn, great contribution!. Please put it as comment with code, and I'll give you a vote. Your answer deserves more attention. – Ricardo Castañeda Dec 11 '14 at 18:15

3 Answers3

9

Twig has a filter called batch that seems to do what each_slice does. In your case, here's what the code would look like:

{% for row in items|batch(4) %}
    <div class="wrapper">
    {% for item in row %}
        {{ item }}
    {% endfor %}
    </div>
{% endfor %}
Maerlyn
  • 33,687
  • 18
  • 94
  • 85
  • 1
    Much cleaner solution and simplifies the logic - lose those ugly if statements from the marked solution! – Alex Apr 15 '16 at 09:26
2

if you're using twig => 1.14.2, you can use divisible by

{% for item in items %}
  {% if loop.index0 is divisible by(4) %}
    <div class="wrapper">
  {% endif %}
    {{ item }}
  {% if loop.index is divisibleby(4) or loop.last %}
    </div>  
  {% endif %}  
{% endfor %}  
devilcius
  • 1,764
  • 14
  • 18
1

Try

{% for item in items %}
{% if loop.index0 % 4 == 0 %}<div class="wrapper">{% endif %}
  {{ item }}
{% if loop.index % 4 == 0 %}</div>{% endif %}
{% endfor %}
Ricardo Castañeda
  • 5,746
  • 6
  • 28
  • 41
geoB
  • 4,578
  • 5
  • 37
  • 70
  • 1
    The answer by @devilcius is worth noting for its final div accomplished by `...or loop.last` – geoB Dec 10 '14 at 22:33