Shopify主题应用扩展中Section Rendering API:获取section_id与自定义参数传递
Shopify Section Rendering API 问题解答
1. 获取动态渲染区块的section_id
- 从应用块上下文直接获取:在应用块的Liquid代码里,使用
block.section.id即可拿到当前块所属区块的section_id。不管区块是动态创建还是用户手动添加的,每个应用块都自带所属区块的上下文,这个属性能直接返回对应的ID,无需依赖预定义的区块文件名。 - 预获取后传递到API请求:如果是在前端发起Section Rendering API请求,先在初始渲染页面的Liquid中通过
block.section.id获取到section_id,再将其作为URL参数或请求体参数带入后续的API调用中,比如生成请求URL时写/sections/{{ block.section.id }}?other_params=xxx。
2. 不依赖content_for_header传递自定义参数
- 通过区块settings传递:在主题应用扩展的块schema中添加自定义配置字段,示例代码:
{% schema %} { "name": "自定义应用块", "settings": [ { "type": "text", "id": "custom_param", "label": "自定义参数" } ] } {% endschema %}
之后在区块Liquid代码中直接通过section.settings.custom_param读取该参数值,无需依赖URL或content_for_header。
- 使用POST请求的请求体:Section Rendering API支持POST方法,你可以将自定义参数放在请求体的
settings字段中,示例请求:
fetch('/sections/your_section_id', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Shopify-Ajax': 'true' }, body: JSON.stringify({ settings: { custom_param: 'your_custom_value' } }) })
对应的区块Liquid中通过section.settings.custom_param即可获取参数。
- 借助元字段存储参数:将需要传递的自定义参数存入店铺、产品或集合的元字段中,在区块Liquid里直接读取,比如
{{ product.metafields.your_app.nested_param }},这种方式适合参数需要和特定资源绑定的场景。
内容的提问来源于stack exchange,提问作者Munashe Nzira
相关产品推荐
相关产品推荐

