You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Drupal Paragraphs下7图循环无限不规则画廊的Twig模板开发问题

错误原因

你现有代码的核心问题是把完整的.gallery容器结构写在了单张图片的遍历循环内部,每遍历1张图就生成1套完整的画廊框架,只填充对应位置的单图,其余位置全部留空,自然无法正常渲染出预期的布局。

正确实现逻辑

需要先把所有上传的图片按7张为一组拆分,每组对应1套画廊结构,再针对每组内部的图片按位置匹配对应的small/tall/big样式,同时自动适配最后一组不足7张的场景。

修复后的Twig代码

{% block content %}
  {# 先把图片数组按7张为一组拆分 #}
  {% set image_groups = content.field_images['#items']|batch(7) %}
  
  {# 遍历每一组图片,每组对应一个画廊容器 #}
  {% for group in image_groups %}
    <div class="gallery">
      <div class="gallery-left">
        <div class="inner-wrapper">
          <div class="inner-left">
            {# 组内第1张图:tall样式 #}
            {% if group[0] is defined %}
            <div class="field__item">
              <img src="{{ group[0]|file_uri|image_style('tall') }}" alt="{{ group[0].alt }}">
            </div>
            {% endif %}
            {# 组内第2张图:small样式 #}
            {% if group[1] is defined %}
            <div class="field__item">
              <img src="{{ group[1]|file_uri|image_style('small') }}" alt="{{ group[1].alt }}">
            </div>
            {% endif %}
          </div>
          <div class="inner-right">
            {# 组内第3张图:tall样式 #}
            {% if group[2] is defined %}
            <div class="field__item">
              <img src="{{ group[2]|file_uri|image_style('tall') }}" alt="{{ group[2].alt }}">
            </div>
            {% endif %}
            {# 组内第4张图:small样式 #}
            {% if group[3] is defined %}
            <div class="field__item">
              <img src="{{ group[3]|file_uri|image_style('small') }}" alt="{{ group[3].alt }}">
            </div>
            {% endif %}
          </div>
        </div>
      </div>
      <div class="gallery-right">
        {# 组内第5张图:small样式 #}
        {% if group[4] is defined %}
        <div class="field__item">
          <img src="{{ group[4]|file_uri|image_style('small') }}" alt="{{ group[4].alt }}">
        </div>
        {% endif %}
        {# 组内第6张图:tall样式 #}
        {% if group[5] is defined %}
        <div class="field__item">
          <img src="{{ group[5]|file_uri|image_style('tall') }}" alt="{{ group[5].alt }}">
        </div>
        {% endif %}
      </div>
      <div class="bottom">
        {# 组内第7张图:big样式 #}
        {% if group[6] is defined %}
        <div class="field__item">
          <img src="{{ group[6]|file_uri|image_style('big') }}" alt="{{ group[6].alt }}">
        </div>
        {% endif %}
      </div>
    </div>
  {% endfor %}
{% endblock %}

注意事项

  • 如果最后一组图片不足7张,对应空缺位置会自动留空,不会抛出错误
  • 代码里的样式名称tall/small/big需要和你后台配置的图片样式名称完全一致,避免生成图片链接失败
  • 如果你用的是Drupal媒体字段而非直接的图片字段,需要调整取图逻辑,先获取媒体实体引用的图片文件再生成样式链接

内容的提问来源于stack exchange,提问作者Tita

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 02:48:02