如何在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
相关产品推荐
相关产品推荐

