我正在從使用 WordPress 和高級自定義欄位創建的圖庫中輸出影像。以下代碼每列顯示兩個影像,列重復,直到沒有更多影像要顯示。我需要設定最多三列,所有影像都顯示在這些列中。
<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="使用回圈渲染三列影像庫,沒有設定影像數量" />
</figure>
{% if loop.index % 2 == 0 or loop.last %}
</div>
{% endif %}
{% endfor %}
</div>
視覺表現:

如何調整代碼以對網站上呈現的列數設定硬性限制?
uj5u.com熱心網友回復:
如果您最多需要 3 列,則可以使用 filter batch。這會將您的陣列分成均勻的塊。
{% 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>
演示
如果story.meta('gallery')不是Iterable,則需要先將其轉換為陣列
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/437660.html
上一篇:我想回傳未定義但得到“{”
下一篇:推送串列中的每個API元素
