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

如何在Shopify中通过商品handle数组获取对应商品数据?

Shopify动态获取关联商品数据问题排查与解决

问题1:JavaScript中使用all_products报错

错误原因

all_products是Shopify的Liquid服务端对象,仅在页面渲染的服务端阶段可用。当代码运行到客户端JavaScript时,Liquid已经执行完毕,客户端环境不存在这个对象,直接调用必然抛出Uncaught ReferenceError。

解决方案

先通过Liquid在服务端把需要的商品数据组装好,再渲染成JSON传递给JavaScript:

{% assign component_handles = product.variants.first.metafields.custom.component_handles %}
{% assign component_products = "" | split: "" %}
{% for handle in component_handles %}
  {% assign target_product = all_products[handle] %}
  {% if target_product %}
    {% assign component_products = component_products | push: target_product %}
  {% endif %}
{% endfor %}

<script>
// 把Liquid组装好的商品数组转为JSON传给JS
const componentProducts = {{ component_products | json }};
console.log(componentProducts);

// 客户端循环处理数据
componentProducts.forEach(item => {
  console.log(item.title, item.handle);
});
</script>

问题2:Liquid循环得到空数组

错误原因

核心是元字段的类型或解析方式不对:

  • 若元字段设为单行文本,存储的["burger", "carbonated-beverage"]会被Liquid识别为普通字符串,而非数组,循环自然无结果;
  • 若元字段类型正确但未正确赋值,也会导致空数组。

解决方案

步骤1:确认元字段类型

在Shopify后台,将component_handles元字段的类型设置为列表(字符串),而非单行文本。这样Liquid会直接将其识别为数组。

步骤2:正确的Liquid循环代码

如果元字段是列表类型:

{% assign component_handles = product.variants.first.metafields.custom.component_handles %}
{% assign component_products = "" | split: "" %}
{% for handle in component_handles %}
  {% assign target_product = all_products[handle] %}
  {% if target_product %}
    {% assign component_products = component_products | push: target_product %}
  {% endif %}
{% endfor %}

{# 测试输出 #}
{{ component_products | json }}

如果元字段是单行文本类型(已存储JSON字符串),需先解析为Liquid数组:

{% assign handles_json = product.variants.first.metafields.custom.component_handles %}
{% assign component_handles = handles_json | json_parse %}
{% assign component_products = "" | split: "" %}
{% for handle in component_handles %}
  {% assign target_product = all_products[handle] %}
  {% if target_product %}
    {% assign component_products = component_products | push: target_product %}
  {% endif %}
{% endfor %}

{# 测试输出 #}
{{ component_products | json }}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:07:06