5

I am trying to loop through all the entries in a section and "group" them into items which are in blocks of 9 then wrap them with some html markup so there will be the following code:

{% set selectedWork = craft.entries.section('selectedWork') %}

<div class="panel panel--1">
  <article class="img-grid">

    {% for item in selectedWork %}
    <section class="img-grid__item">
      {{ item.title }}
    </section>
    {% endfor %}

  </article>
</div><!-- END .panel -->

The outer <div class="panel panel-1"> and <article> tags need to wrap round the first 9 items then then next 9 etc. etc. Also the panel--1 needs to increment so that each panel goes in order so panel--1 holds 1-9 items then panel--2 holds 9-18 items etc. Is this possible using some kind of array splice or something?

1 Answer 1

10

The array slice something you are looking for is Twig's batch filter. Here's how you'd set up the groups and use loop.index to generate the class name.

{# Use the `find()` method to return an array of EntryModels #}
{% set selectedWork = craft.entries.section('selectedWork').find() %}

{# Group entries using the `batch` filter #}
{% set selectedWorkGrouped = selectedWork|batch(9) %}

{% for group in selectedWorkGrouped %}

    {# Set class using the loop index from outer loop #}
    {% set panelClass = 'panel--' ~ loop.index %}

    <div class="panel {{ panelClass }}">

        {% for entry in group %}
            <section class="img-grid__item">
                {{ entry.title }}
            </section>
        {% endfor %}

    </div

{% endfor %}
1
  • 1
    Wow I didn't know about the batch filter, this solution worked like a charm. Thank you very much.
    – Gareth
    Commented Jan 23, 2015 at 19:11

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.