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 >
{% for image in story.meta( 'gallery' ) %}
{% if loop.index % 2 == 1 %}
<div >
{% 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:
How can I adjust the code to set a hard limit on the number of columns rendered on the site?
CodePudding user response:
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 >
{% for images in images|batch(images_per_col) %}
<div >
{% for image in images %}
<figure>
<img src="{{ image }}" />
</figure>
{% endfor %}
</div>
{% endfor %}
</div>
If story.meta('gallery')
is not Iterable
, you would need to convert this to an array first