Liquid中使用变量索引调用集合无输出问题排查
嘿,我帮你找到了两个关键问题,咱们一步步来解决:
1. 先修正明显的语法错误
你第二行的Liquid标签没闭合,少了结尾的%},这会直接导致Liquid解析失败,后续的变量逻辑全乱掉:
原错误代码:
{% assign _product_tag = product.collections[0].title}
修正后:
{% assign _product_tag = product.collections[0].title %}
2. 核心问题:用错了Collection的索引键
Liquid里的collections对象是通过collection的handle(也就是URL友好的标识符,通常全小写、空格转成连字符)来访问的,而不是显示用的title。
你静态写collections['Beans']能生效,是因为这个Beans刚好是目标collection的handle;但你用product.collections[0].title拿到的是显示名称,万一title和handle不一致(比如title是"Organic Beans",handle是"organic-beans"),collections[_product_tag]就找不到对应的集合,自然输出为空。
正确的做法是获取collection的handle而非title:
{% assign _product_id = product.id %} {% assign _product_tag = product.collections[0].handle %} {% assign _product_name = product.title %} {{_product_tag}} {% assign pagla_array = collections[_product_tag].products %} {{ pagla_array.first.title }}
额外的容错建议(可选)
为了避免产品没归属任何分类、或者分类下没有产品的情况报错,可以加一层判断:
{% if product.collections.size > 0 %} {% assign _product_collection = product.collections[0] %} {% assign pagla_array = collections[_product_collection.handle].products %} {% if pagla_array.size > 0 %} {{ pagla_array.first.title }} {% else %} 该分类下暂无产品 {% endif %} {% else %} 该产品未归属任何分类 {% endif %}
内容的提问来源于stack exchange,提问作者Newaz Sharif
相关产品推荐
相关产品推荐

