'Use loop to render three column image gallery with no set number of images

I am outputting images from a gallery created with WordPress and Advanced Custom Fields. The following code is displaying two images per column, with the columns repeating until there are no more images to display. I am needing to set a max of three columns with all of the images displayed within those columns.

<div class="grid">
  {% for image in story.meta( 'gallery' ) %}
    {% if loop.index % 2 == 1 %}
      <div class="post__gallery-column">
    {% endif %}
        <figure>
          <img src="{{ Image(image) }}" width="{{ Image(image).width }}" height="{{ Image(image).height }}" alt="{{ Image(image).alt }}" />
        </figure>
    {% if loop.index % 2 == 0 or loop.last %}
      </div>
    {% endif %}
  {% endfor %}
</div>

Visual representation:

Image columns example

How can I adjust the code to set a hard limit on the number of columns rendered on the site?



Solution 1:[1]

If you want a max of 3 columns, you could use the filter batch. This splits your array in even chunks.

{% set max_cols = 3 %}
{% set images_per_col = (images|length / max_cols)|round(0, 'ceil') %}

<div class="grid">
    {% for images in images|batch(images_per_col) %}
    <div class="post__gallery-column">
        {% for image in images %}
        <figure>
            <img src="{{ image }}" />
        </figure>
        {% endfor %}
    </div>
    {% endfor %}
</div>

demo


If story.meta('gallery') is not Iterable, you would need to convert this to an array first

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 DarkBee