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

如何在Shopify Liquid模板中按Z到A展示产品?代码无效求助

如何在Liquid模板中按Z到A逆序列出产品?

你的代码失效的核心原因是:paginate标签仅能作用于Shopify的集合对象(比如collections.all.products),而sort+reverse过滤器会把集合转换为数组,导致分页逻辑无法正常执行。

解决方案1:无分页需求(或产品数量少于分页阈值)

如果不需要分页,直接去掉paginate标签即可,代码如下:

{% assign myproducts = collections.all.products | sort: 'title' | reverse %}
{% for product in myproducts %}
  {% include 'product-thumb' with size:'oneThird', thumbSize:'thirds' %} 
{% endfor %}

解决方案2:需要分页的场景

方式A:在循环中使用reversed关键字

这种方式保留paginate对集合的原生支持,仅在循环时反向遍历已按标题升序排序的集合:

{% paginate collections.all.products by 1000 %}
  {% for product in collections.all.products | sort: 'title' reversed %}
    {% include 'product-thumb' with size:'oneThird', thumbSize:'thirds' %} 
  {% endfor %}
{% endpaginate %}

方式B:手动处理数组分页(完整全局排序)

如果需要对全部产品先做全局Z-A排序再分页,需要手动实现分页逻辑(因为paginate不支持数组):

{% assign all_products = collections.all.products | sort: 'title' | reverse %}
{% assign page_size = 1000 %}
{% assign current_page = request.params.page | default: 1 | plus: 0 %}
{% assign start_index = (current_page | minus: 1) | times: page_size %}
{% assign paginated_products = all_products | slice: start_index, page_size %}

<!-- 输出产品 -->
{% for product in paginated_products %}
  {% include 'product-thumb' with size:'oneThird', thumbSize:'thirds' %} 
{% endfor %}

<!-- 手动渲染分页导航 -->
{% assign total_products = all_products.size %}
{% if total_products > page_size %}
  {% assign total_pages = total_products | divided_by: page_size %}
  {% if total_products | modulo: page_size != 0 %}
    {% assign total_pages = total_pages | plus: 1 %}
  {% endif %}
  <div class="pagination">
    {% if current_page > 1 %}
      <a href="?page={{ current_page | minus: 1 }}">上一页</a>
    {% endif %}
    {% for page in (1..total_pages) %}
      {% if page == current_page %}
        <strong>{{ page }}</strong>
      {% else %}
        <a href="?page={{ page }}">{{ page }}</a>
      {% endif %}
    {% endfor %}
    {% if current_page < total_pages %}
      <a href="?page={{ current_page | plus: 1 }}">下一页</a>
    {% endif %}
  </div>
{% endif %}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 22:00:58