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

Shopify如何从多产品metafield中单独调用指定关联产品

Shopify产品列表Metafield按索引单独调用产品实现方法

你创建的"List of products"类型metafield存储的是产品对象数组,Liquid支持直接通过数组下标访问指定位置的元素,不需要遍历全部产品即可单独取出对应产品,适配Bootstrap自定义布局需求。

配置示例截图
产品添加示例截图

核心规则

  • 数组索引从0开始计数:后台添加的第一个关联产品对应索引0,第二个对应索引1,后续产品依次顺延
  • 取值前必须做非空判断,避免后台添加的产品数量不足时页面渲染报错
  • 循环遍历关联产品时,不要把循环变量命名为product,会覆盖当前页面全局的产品对象,导致数据错乱

场景1:单独调用指定位置的单个产品

直接通过数组名[索引]的方式取值,每个产品可以单独放到你预先写好的Bootstrap div容器中,示例代码:

{% if product.metafields.my_fields.custom_img.value != blank  %}
  {% assign recommended_products = product.metafields.my_fields.custom_img.value %}
  
  <!-- 第1个关联产品(索引0)对应容器 -->
  <div class="col-12 mb-4">
    {% if recommended_products[0] != blank %}
      <a href="{{ recommended_products[0].url }}" class="d-block">
        {{ recommended_products[0].featured_image | image_url: width: 800 | image_tag: class: 'img-fluid' }}
        <h5 class="mt-2">{{ recommended_products[0].title }}</h5>
      </a>
    {% endif %}
  </div>

  <!-- 第2个关联产品(索引1)对应容器 -->
  <div class="col-6">
    {% if recommended_products[1] != blank %}
      <a href="{{ recommended_products[1].url }}" class="d-block">
        {{ recommended_products[1].featured_image | image_url: width: 400 | image_tag: class: 'img-fluid' }}
        <p class="mt-2">{{ recommended_products[1].title }}</p>
      </a>
    {% endif %}
  </div>
{% endif %}

如果只需要展示指定的某1个产品,只保留对应索引的代码块即可。


场景2:遍历产品时按索引匹配不同布局

如果需要批量渲染所有关联产品,同时给不同位置的产品匹配不同Bootstrap样式,可以在循环中通过forloop.index0(从0开始的索引)做判断,示例代码:

{% if product.metafields.my_fields.custom_img.value != blank  %}
  <h3>Recommended Products</h3>
  <div class="row">
    {% assign recommended_products = product.metafields.my_fields.custom_img.value %}
    {% for product_item in recommended_products  %}
      {% case forloop.index0 %}
        {% when 0 %}
          <!-- 第一个产品占整行 -->
          <div class="col-12 mb-3">
            <a href="{{ product_item.url }}">
              {{ product_item.featured_image | image_url: width: 900 | image_tag: class: 'img-fluid' }}
            </a>
          </div>
        {% when 1 %}
        {% when 2 %}
          <!-- 第二、第三个产品各占半行 -->
          <div class="col-6 mb-3">
            <a href="{{ product_item.url }}">
              {{ product_item.featured_image | image_url: width: 450 | image_tag: class: 'img-fluid' }}
            </a>
          </div>
        {% else %}
          <!-- 其余产品各占1/3行 -->
          <div class="col-4 mb-3">
            <a href="{{ product_item.url }}">
              {{ product_item.featured_image | image_url: width: 300 | image_tag: class: 'img-fluid' }}
            </a>
          </div>
      {% endcase %}
    {% endfor %}
  </div>
{% endif %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 09:39:17