[英]How to use a variable name inside of liquid shortcode to render a section file in a template file for Shopify?
客观的:
我想使用变量作为部分文件的名称在template
内呈现 Shopify section
。 IE
例子
模板: templates/parent.liquid
部分: sections/child.liquid
当variableName = 'child'
时,尝试在parent.liquid
中渲染(包括) child.liquid
context: *child*
可以是任何东西——在我的主题的特定用例中,我分配variableName = page.handle
。 如果page.handle
与现有产品供应商匹配并且sections/[page.handle].liquid
存在,我将其包含在页面中。
为什么? 如果这种提议的从当前页面派生的动态文件名的编程方法,我想避免使用硬编码的可用节文件列表来代替。
以下代码将 go 内templates/parent.liquid
这有效(硬编码带引号的字符串):
但是,我想不惜一切代价避免硬编码的文件名。
{% section 'child' %}
这些都会引发错误(任何形式的动态文件名):
{% section variableName %}
{% section {{ variableName }} %}
{% section 'variableName' %}
{% section "'" + variableName + "'" %}
{% section variableName %}
{% section "{{ variableName }}" %}
{% section [variableName] %}
编辑更多错误
{% render variableName %}
标签“render”中的语法错误 - 模板名称必须是带引号的字符串
{% include variableName %}
寻找一个片段,而不是一个部分
{% include sections.variableName %}
Liquid 错误:标签“include”中的参数错误 - 非法模板名称
{% include sections.[variableName] %}
Liquid 错误:标签“include”中的参数错误 - 非法模板名称
研究我通过 Google 找到的最接近的文章是https://community.shopify.com/c/Shopify-Design/Dynamic-Liquid-Variable-inside-Liquid-tag/td-p/162451
伪答案我正在寻找一个可行的解决方案:
{% include sections.[page.handle] %}
使用include
或render
将变量传递给section
是不可能的
在节外创建的变量在节内不可用。 同样,在节中创建的变量在节外不可用。 如果一个部分包含一个片段,则该片段可以访问该部分中的变量。
使用变量作为文件名不适用于render
。 它仅适用于include
例如
{% assign fileName = "product-" | append: product.handle %}
{% capture productLinkContent %}
{% include fileName %}
{% endcapture %}
{% unless productLinkContent contains "Liquid error: Could not find asset " %}
{% include fileName %}
{% else %}
do something else
{% endunless %}
所以,在你的template/parent.liquid
调用{% section 'parent-template' %}
并且在parent-template.liquid
中使用include
如上所述。
原因是您需要确保section
文件存在以便它不会破坏 shopify 定制器,并且现在无法使用流动代码检查。
如果您真的想坚持使用可变解决方案,这是另一种解决方案,即您使用if-else
/ case - when
语句传递文件;
{% assign fileName = "product-" | append: product.handle %}
{% case fileName %}
{% when 'product-a' %}
{% section 'product-a' %}
{% when 'product-b' %}
{% section 'product-b' %}
{% else %}
do something else
{% endcase %}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.