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

Shopify自定义集合模板按'Hydrate'标签筛选商品循环展示问题

Shopify自定义集合模板筛选指定标签商品解决方案

问题描述

需要在Shopify的collection.custom.liquid自定义集合模板中,筛选并展示所有带Hydrate标签的商品,先后遇到无输出、商品重复展示的问题。

问题1:初始代码无输出

最初编写代码如下,确认标签配置、大小写匹配的前提下无内容输出:

{% for product in collection.products %}   
{% if product.tags contains "Hydrate" %} 
 Do Something
{% endif %}
{% endfor %}

无输出原因:这段代码仅遍历当前集合下的商品,如果当前集合本身没有关联带Hydrate标签的商品,就不会有内容输出。如果你的需求是只展示当前集合内带指定标签的商品,需要先确认该集合已经绑定了对应商品;如果需要拉取全站所有符合标签的商品,需要调整遍历对象为全站商品库。

问题2:调整后商品重复展示

后续调整代码移到分页逻辑外后,出现同标签商品重复展示5次的问题,代码如下:

{% for product in collection.products %} 
  {% for product in products %}
    {% if product.tags contains "Hydrate" %} 
        <p>{{ product.title }}</p>
    {% endif %}
  {% endfor %}
{% endfor %}

问题原因:代码存在两层冗余for循环嵌套,外层遍历当前集合的商品列表,内层又遍历全站商品列表。假设当前集合默认有5个商品,外层就会循环5次,每次内层都输出一遍所有符合要求的商品,最终就会重复展示5次。

最终可用代码

方案1:仅筛选当前集合内带Hydrate标签的商品

{% assign products = collection.products %}
  {% for product in products %}
    {% if product.tags contains "Hydrate" %} 
        <p>{{ product.title }}</p>
  {% endif %}
{% endfor %}

方案2:拉取全站所有带Hydrate标签的商品(不受当前集合限制)

<!-- 如需展示超过50个商品,可调整by后的数值,最高支持250 -->
{% paginate collections.all.products by 100 %}
{% for product in collections.all.products %}
  {% if product.tags contains "Hydrate" %}
    <p>{{ product.title }}</p>
  {% endif %}
{% endfor %}
{% endpaginate %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 03:36:02