Shopify Liquid如何不转数组合并集合实现售罄商品排序分页
你当前的代码存在核心逻辑错误:直接将原集合赋值给topcol/bottomcol,循环内的赋值操作没有修改集合本身,最终合并的是两份完全相同的原集合,完全没有达到过滤排序的效果。同时Shopify的paginate标签仅支持原生资源对象(如collection.products、blog.articles等),不支持自定义数组,这是你报错的根本原因。
以下是完全符合需求的可行实现方案:
方案:自定义过滤数组 + 手动实现分页
无需修改后台配置,库存变动可自动调整排序,不需要额外的第三方工具支持。
步骤1:正确生成排序后的商品数组
{% comment %} 初始化两个空数组,分别存放优先展示、靠后展示的商品 {% endcomment %} {% assign available_products = '' | split: '' %} {% assign sold_out_products = '' | split: '' %} {% comment %} 遍历原集合,分类存入对应数组 {% endcomment %} {% for product in collection.products %} {% if product.available or product.tags contains "_boost" %} {% assign available_products = available_products | push: product %} {% else %} {% assign sold_out_products = sold_out_products | push: product %} {% endif %} {% endfor %} {% comment %} 合并数组,优先展示的在前,售罄的在后 {% endcomment %} {% assign sorted_products = available_products | concat: sold_out_products %}
这里用到了你提到的split方法实现空数组初始化,是Liquid中创建自定义数组的标准实现方式。
步骤2:手动实现分页逻辑
{% comment %} 分页基础参数配置 {% endcomment %} {% assign per_page = section.settings.products_per_page %} {% assign current_page = request.parameters.page | default: 1 | plus: 0 %} {% assign total_products = sorted_products.size %} {% assign total_pages = total_products | divided_by: per_page | ceil %} {% assign offset = (current_page | minus: 1) | times: per_page %} {% comment %} 遍历当前页的商品 {% endcomment %} {% for product in sorted_products limit: per_page offset: offset %} {% comment %} 此处替换为你原有的商品卡片渲染逻辑 {% endcomment %} {% endfor %} {% comment %} 分页导航(可根据你的UI需求自定义样式) {% endcomment %} {% if total_pages > 1 %} <div class="pagination"> {% if current_page > 1 %} <a href="{{ collection.url }}?page={{ current_page | minus: 1 }}">上一页</a> {% endif %} {% for page in (1..total_pages) %} {% if page == current_page %} <span class="active">{{ page }}</span> {% else %} <a href="{{ collection.url }}?page={{ page }}">{{ page }}</a> {% endif %} {% endfor %} {% if current_page < total_pages %} <a href="{{ collection.url }}?page={{ current_page | plus: 1 }}">下一页</a> {% endif %} </div> {% endif %}
注意事项
- 如果你的集合商品数量超过50个,需要先解除Liquid的遍历限制:在集合查询的URL后加
&limit=250,最多支持250个商品的集合排序,超过250个的场景需要结合Shopify API实现。 - 该方案完全适配你的需求:商品恢复库存后会自动被分到
available_products数组,回到原有排序位置,无需手动修改。
内容的提问来源于stack exchange,提问作者Preben F
相关产品推荐
相关产品推荐

