我想在模板中包含代码片段,但只有在代码片段文件存在的情况下。有什么办法可以做到吗?Shopify液体:我如何有条件地在Shopify液体中添加片段?
现在,我只是用:
{% include 'snippetName' %}
但这引发错误:
Liquid error: Could not find asset snippets/snippetName.liquid
我之所以需要这样的功能,因为我有一个后台进程,后来增加了片段上。
我想在模板中包含代码片段,但只有在代码片段文件存在的情况下。有什么办法可以做到吗?Shopify液体:我如何有条件地在Shopify液体中添加片段?
现在,我只是用:
{% include 'snippetName' %}
但这引发错误:
Liquid error: Could not find asset snippets/snippetName.liquid
我之所以需要这样的功能,因为我有一个后台进程,后来增加了片段上。
自己有这个问题。这是我的解决方案:
{% capture the_snippet_content %}{% include the_snippet %}{% endcapture %}
{% unless the_snippet_content contains "Liquid error" %}
{% include reviews_snippet %}
{% endunless %}
基本上捕获代码段的内容作为一个变量。 如果没有片断Shopify生成错误:
Liquid error: Could not find asset snippets/caroline-flint-reviews.liquid
所以检查,看它是否产生的......如果是这样不打印的片断 :d
当然,如果你打算这样会破坏您的片段包含“液体错误”,或者Shopify是否曾更改错误信息。
@vovafeldman不知道为什么你不能有一个空白的片段,但没有文件存在。
我能想到的唯一的其他选择是因为您使用BG流程来生成代码段(并且我假设上传代码段),您可以随时使用模板API上传包含片段的模板版本与此同时。
或者,您可以创建自己的标签,在尝试处理文件之前检查文件的存在。
https://github.com/Shopify/liquid/wiki/Liquid-for-Programmers#create-your-own-tags
如果您从“根”管理液体,则可以创建自己的标签。 Shopify已定义了所有标签,并且您无法创建新标签。 – alexandresaiz
扩展Jon的答案;
创建一个名为snippet.liquid
{% capture snippet_content %}{% include snippet %}{% endcapture %}
{% unless snippet_content contains "Liquid error" %}
{{ snippet_content }}
{% endunless %}
然后,当你想包括一个文件只如果它存在
{% include 'snippet' with 'filename_of_include' %}
非常整齐的实施。 – Carlton
这是一个伟大的答案! – vovafeldman
非常有用。使用此功能创建基于句柄的片段路由系统 – Leland