使用 Twig 循环以嵌套结构输出 WordPress/ACF 个图库

Use Twig loop to output WordPress/ACF image gallery in nested structure

我正在使用以下代码从 WordPress 和使用 Timber 插件的高级自定义字段输出图片库。

{% if story.meta( 'gallery' ) %}
  <div class="story__gallery">
    <div class="gallery__row">
    {% for image in story.meta( 'gallery' ) %}
      {% if Image(image).width > Image(image).height %}
        {% set dimension = 'gallery__item--horizontal' %}
      {% else %}
        {% set dimension = 'gallery__item--vertical' %}
      {% endif %}
      <figure class="gallery__item gallery__item--{{ Image(image).id }} {{ dimension }}">
        <img src="{{ Image(image) }}" width="{{ Image(image).width }}" height="{{ Image(image).height }}" alt="{{ Image(image).alt }}" />
      </figure>
      {% if loop.index is divisible by(3) and not loop.last %}
        </div><div class="gallery__row">
      {% endif %}
    {% endfor %}
    </div>
  </div>
{% endif %}

此版本的代码有效,但现在我需要实现一些逻辑以使用以下 HTML 结构输出图库。

<div class="story__gallery">
  <div class="gallery__row">
    <figure class="gallery__item gallery__item--large"></figure>
    <div class="gallery__cluster">
      <figure class="gallery__item gallery__item--small"></figure>
      <figure class="gallery__item gallery__item--small"></figure>
    </div>
  </div>
</div>

我将如何使用 loop.index 将两个小图形包装在 gallery__cluster div 中并将其正确输出到 gallery__row 容器中?

我会在循环外设置一个变量并每次将其递增 1,因为每次递增循环都需要做不同的事情。每 3 个循环重置一次。这是很多 if 语句,但它完成了工作。请注意,我没有测试以下内容,因为我没有与您的组件相匹配的组件来测试,但我认为您可以让它工作。

{% set rowIndex = 0 %}
    
{% if story.meta( 'gallery' ) %}
  <div class="story__gallery">
    {% for image in story.meta( 'gallery' ) %}
      {% set rowIndex = rowIndex + 1 %}
      {% if rowIndex == 1 %}
        <div class="gallery__row">
          <figure class="gallery__item gallery__item--large">
            <img src="{{ Image(image) }}" width="{{ Image(image).width }}" height="{{ Image(image).height }}" alt="{{ Image(image).alt }}" />
          </figure>
          {% if loop.last %}
            </div>
          {% endif %}
      {% endif %}
      {% if rowIndex == 2 %}
        <div class="gallery__cluster">
          <figure class="gallery__item gallery__item--small">
            <img src="{{ Image(image) }}" width="{{ Image(image).width }}" height="{{ Image(image).height }}" alt="{{ Image(image).alt }}" />
          </figure>
        {% if loop.last %}
          </div>
          </div>
        {% endif %}
      {% endif %}
      {% if rowIndex == 3 %}
        <figure class="gallery__item gallery__item--small">
          <img src="{{ Image(image) }}" width="{{ Image(image).width }}" height="{{ Image(image).height }}" alt="{{ Image(image).alt }}" />
        </figure>
        </div>
        </div>
        {% set rowIndex = 0 %}
      {% endif %}
    {% endfor %}
  </div>
{% endif %}