Shopify教程:如何在多个Schema中复用选择器设置
问题描述
我有一个路径为sections/two-col-cta.liquid的区块,其Schema定义如下:
{% schema %} { "name": "Two Column CTA", "class": "section", "settings": [ { "type": "select", "id": "color_select", "options": [ { "value": "option_1", "label": "option_1" }, { "value": "option_2", "label": "option_2" }, { "value": "option_3", "label": "option_3" }, { "value": "option_4", "label": "option_4" }, { "value": "option_5", "label": "option_5" } ], "default": "image_first", "label": "t:sections.two-col-content-img.settings.layout.label", "info": "t:sections.two-col-content-img.settings.layout.info" } ] } {% endschema %}
这个名为color_select的选择器设置在多个不同区块(sections/*.liquid文件)中重复定义。请问能否全局定义该设置,之后直接引入到各区块中,无需每次重复编写?
解决方案
Shopify Liquid本身不支持直接全局引入Schema设置项,但可以通过片段复用的方式实现代码复用,不用每次重复编写:
步骤1:创建全局设置片段
在主题的snippets目录下新建一个global-color-select.liquid文件,将color_select的完整设置JSON内容放入其中:
{ "type": "select", "id": "color_select", "options": [ { "value": "option_1", "label": "option_1" }, { "value": "option_2", "label": "option_2" }, { "value": "option_3", "label": "option_3" }, { "value": "option_4", "label": "option_4" }, { "value": "option_5", "label": "option_5" } ], "default": "image_first", "label": "t:sections.two-col-content-img.settings.layout.label", "info": "t:sections.two-col-content-img.settings.layout.info" }
步骤2:在区块中引入片段
在需要使用color_select的区块Schema里,用{% render %}标签引入这个片段即可:
{% schema %} { "name": "Two Column CTA", "class": "section", "settings": [ {% render 'global-color-select' %} // 这里可以添加其他自定义设置项,注意JSON语法的逗号分隔 ] } {% endschema %}
进阶:灵活调整翻译文本
如果不同区块需要不同的label或info翻译键,可以给片段传递参数:
- 修改
snippets/global-color-select.liquid的内容,用Liquid变量替换固定的翻译键:
{ "type": "select", "id": "color_select", "options": [ { "value": "option_1", "label": "option_1" }, { "value": "option_2", "label": "option_2" }, { "value": "option_3", "label": "option_3" }, { "value": "option_4", "label": "option_4" }, { "value": "option_5", "label": "option_5" } ], "default": "image_first", "label": "{{ label_key | default: 't:sections.two-col-content-img.settings.layout.label' }}", "info": "{{ info_key | default: 't:sections.two-col-content-img.settings.layout.info' }}" }
- 在引入片段时传递自定义参数:
{% schema %} { "name": "Another Section", "class": "section", "settings": [ {% render 'global-color-select', label_key: 't:sections.another-section.settings.color.label', info_key: 't:sections.another-section.settings.color.info' %} ] } {% endschema %}
内容的提问来源于stack exchange,提问作者Matthew Dejager
相关产品推荐
相关产品推荐

