Looping through collection in sets

Hello. I was trying to fetch images from a collection of pages to use in a slider. The tricky part was that I wanted each slide to have three images so that the final code would look like this:

<div class="slider">
    <div class="slide">
        <img src="logo-1.svg" alt="">
        <img src="logo-2.svg" alt="">
        <img src="logo-3.svg" alt="">
    <div class="slide">
        <img src="logo-1.svg" alt="">
        <img src="logo-2.svg" alt="">
        <img src="logo-3.svg" alt="">
    </div>
    ...
</div>

I ended up using the following code that seems to work but seems a little over the top.

<?php $brands = page('brands')->children()->visible(); ?>
    <div class="slider">
    <?php $i = 0 ?>
    <?php foreach($brands as $brand): ?>
        <?php $logo = $brand->logo()->toFile();
        if($logo):         
            if($i % 3 == 0): ?>
                <div class="slide">
            <?php endif ?>
                <img src="<?= $logo->url() ?>" alt="">
            <?php if(($i + 1) % 3 == 0): ?>
                </div>
            <?php endif ?>                
       <?php endif ?>
       <?php $i++ ?>
    <?php endforeach ?>
    </div>

So I was wondering if there is an easier way to do this by dividing the collection into chunks of three and then acting upon them.

Thanks in advance!

Yes, there is the chunk() method: https://getkirby.com/docs/toolkit/api/collection/chunk

There is one downside though: If an image doesn’t exist, the setup will not work.

Perfect! Thank you very much!

However, see my edited remark.

The safer way of doing this would be to slice up an image collection.

Will keep that in mind. Thanks again!

What you could to solve this, is use a custom filter that only returns those children that return an image like this:

$brands = page('brands')->children()->visible()->filter(function($child) {
  return $child->logo()->toFile();
})->chunk(3);
1 Like