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

如何在Shopify Liquid循环中添加多个集合并展示主题设置选中集合的产品?

在Shopify Liquid中循环多个集合的产品

你的代码问题在于,当你把两个集合放到数组col里后,直接调用col.products是无效的——因为col是一个集合数组,数组本身并没有products属性,你需要遍历数组里的每个集合,再去访问它们的产品列表。下面给你两种实用的解决方案:

方案1:嵌套循环(适合需要区分不同集合的场景)

如果需要给每个集合单独加标题、样式区分,用嵌套循环最直观:

{% assign selected_collections = [collections[settings.collection1], collections[settings.collection2]] %}

{% for collection in selected_collections %}
  {% if collection %} <!-- 关键:防止未选择集合时出现错误 -->
    <h3>{{ collection.title }}</h3>
    <div class="collection-products">
      {% for product in collection.products %}
        <div class="product-card">
          <a href="{{ product.url }}">
            <img src="{{ product.featured_image | img_url: 'medium' }}" alt="{{ product.title }}">
            <p>{{ product.title }}</p>
            <span>{{ product.price | money }}</span>
          </a>
        </div>
      {% endfor %}
    </div>
  {% endif %}
{% endfor %}

方案2:合并产品数组后统一循环(适合无需区分集合的场景)

如果只想把所有集合的产品放在一起展示,不需要区分来源,可以先把多个集合的产品数组合并成一个,再循环:

{% assign col1 = collections[settings.collection1] %}
{% assign col2 = collections[settings.collection2] %}

{% assign all_products = blank %}

<!-- 逐步合并产品数组,避免空值报错 -->
{% if col1 %}
  {% assign all_products = col1.products %}
{% endif %}
{% if col2 %}
  {% if all_products == blank %}
    {% assign all_products = col2.products %}
  {% else %}
    {% assign all_products = all_products | concat: col2.products %}
  {% endif %}
{% endif %}

<!-- 如果需要去重(两个集合有重复产品),可以加uniq过滤器 -->
{% assign all_products = all_products | uniq %}

{% for product in all_products %}
  <div class="product-card">
    <a href="{{ product.url }}">
      <img src="{{ product.featured_image | img_url: 'medium' }}" alt="{{ product.title }}">
      <p>{{ product.title }}</p>
      <span>{{ product.price | money }}</span>
    </a>
  </div>
{% endfor %}

重要提示

  • 一定要加上{% if collection %}的判断:如果用户在主题设置中没有选择某个集合,collections[settings.collectionX]会返回nil,直接循环会导致Liquid报错。
  • 合并数组时用concat过滤器,但要确保被合并的数组不是空值,否则会触发错误。
  • 如果需要对产品排序,可以在合并后添加排序过滤器,比如{% assign all_products = all_products | sort: 'title' %}。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:40:55