如何在Liquid文件中将Product对象推入数组?代码失效求助
问题排查与正确实现方法
你的代码核心问题
- 数组初始化错误:
{% assign notebooks = null | sort %}无法生成可用的空数组,Liquid中需要通过特定方式创建空数组。 - 错误的数组添加方式:
- 第一段代码用
append拼接,这是字符串操作,会把Product对象转为字符串(而非保留对象结构),导致后续无法正常遍历产品属性。 - 第二段代码用
push过滤器,但Liquid中不存在push过滤器,无法实现数组元素添加。
- 第一段代码用
- 额外逻辑注意:
handle contains newProduct.title的判断逻辑需要确认是否符合你的需求(当前页面handle包含产品标题),若逻辑颠倒需调整。
正确实现步骤
1. 初始化空数组
Liquid中创建空数组的标准方式是用空字符串拆分:
{% assign notebooks = '' | split: '' %}
2. 遍历产品并添加到数组
使用concat过滤器(需将单个产品包装为数组后拼接),这样能保留Product对象的完整结构:
{% assign notebooks = notebooks | concat: [newProduct] %}
3. 完整修正代码
{% comment %} 初始化空数组 {% endcomment %} {% assign notebooks = '' | split: '' %} {% comment %} 遍历目标集合的所有产品(无需分页,直接遍历即可) {% endcomment %} {% for newProduct in collections['entire-collection'].products %} {% assign variant_details = newProduct.selected_or_first_available_variant %} {% comment %} 按你的业务条件筛选产品 {% endcomment %} {% if handle contains newProduct.title and newProduct.id != current_id %} {% if current_price > newProduct.price and newProduct.available %} {% comment %} 将符合条件的产品添加到数组 {% endcomment %} {% assign notebooks = notebooks | concat: [newProduct] %} {% comment %} 你的其他变量赋值逻辑 {% endcomment %} {% assign product = newProduct %} {% assign current_variant = newProduct.selected_or_first_available_variant %} {% endif %} {% endif %} {% endfor %} {% comment %} 遍历新生成的数组,展示产品 {% endcomment %} {% if notebooks.size > 0 %} <div class="matched-products"> <h3>匹配产品列表</h3> <ul> {% for item in notebooks %} <li> <a href="{{ item.url }}">{{ item.title }}</a> <span>{{ item.price | money }}</span> </li> {% endfor %} </ul> </div> {% else %} <p>未找到匹配的产品</p> {% endif %}
4. 第二段代码的修正(单个产品添加到数组)
如果只是想把当前product对象添加到数组,代码应为:
{% assign notebooks = '' | split: '' %} {% assign notebooks = notebooks | concat: [product] %}
内容的提问来源于stack exchange,提问作者Anoop
相关产品推荐
相关产品推荐

