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

如何在Liquid文件的Shopify schema标签中加载shop.metafields值为选项?

问题根源

Shopify的{% schema %}标签是静态JSON配置,主题编辑器加载时会优先解析它为静态结构,不会执行内部的Liquid语法(比如for循环、变量输出),所以你直接在options里写Liquid循环的方法是无效的。

正确实现方案

我们可以通过Liquid预先生成完整的Schema JSON字符串,再传递给{% schema %}标签,具体步骤如下:

1. 处理元字段数据

首先确保元字段是数组格式,如果是逗号分隔的字符串,先转成数组:

{% comment %} 处理元字段:如果是字符串则拆分,否则直接用数组 {% endcomment %}
{% assign raw_options = shop.metafields.global.convertcart_blockIds %}
{% if raw_options contains ',' %}
  {% assign optionsArray = raw_options | split: ',' %}
{% else %}
  {% assign optionsArray = raw_options %}
{% endif %}

2. 生成Options的JSON片段

用Liquid循环拼接出符合JSON格式的options数组字符串:

{% comment %} 生成options的JSON字符串 {% endcomment %}
{% assign options_json = '' %}
{% for option in optionsArray %}
  {% comment %} 转义选项中的特殊字符,避免JSON语法错误 {% endcomment %}
  {% assign cleaned_option = option | strip | escape %}
  {% assign option_item = '{"value": "' | append: cleaned_option | append: '", "label": "' | append: cleaned_option | append: '"}' %}
  
  {% if forloop.first %}
    {% assign options_json = option_item %}
  {% else %}
    {% assign options_json = options_json | append: ', ' | append: option_item %}
  {% endif %}
{% endfor %}

3. 拼接完整Schema并输出

把预生成的options片段插入到Schema结构中,再用{% capture %}生成完整的JSON字符串,最后传递给{% schema %}:

{% capture full_schema %}
{
  "name": "Recommended Products",
  "tag": "section",
  "target": "section",
  "settings": [
    {
      "type": "richtext",
      "id": "heading",
      "label": "Heading"
    },
    {
      "type": "select",
      "id": "blockId",
      "label": "Block ID",
      "info": "Select an option",
      "options": [{{ options_json }}]
    }
  ]
}
{% endcapture %}

{% schema %}
{{ full_schema }}
{% endschema %}
关键注意事项
  • 确保元字段是数组类型(Shopify后台创建元字段时可选择List of strings类型),如果是普通字符串,必须用split转成数组才能循环。
  • 一定要用escape过滤器处理选项中的特殊字符(比如双引号、斜杠),否则会导致JSON语法错误,Schema无法正常解析。
  • 前端script标签无法修改Schema:Schema是在主题编辑器加载前由Shopify后端解析的,前端JS代码无法影响这个过程,所以这种方法行不通。

内容的提问来源于stack exchange,提问作者D.K. Goutham Kishore

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 03:47:49