2013-02-02 126 views
8

我想在模板中包含代码片段,但只有在代码片段文件存在的情况下。有什么办法可以做到吗?Shopify液体:我如何有条件地在Shopify液体中添加片段?

现在,我只是用:

{% include 'snippetName' %} 

但这引发错误:

Liquid error: Could not find asset snippets/snippetName.liquid 

我之所以需要这样的功能,因为我有一个后台进程,后来增加了片段上。

回答

17

自己有这个问题。这是我的解决方案:

{% 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是否曾更改错误信息。

+0

这是一个伟大的答案! – vovafeldman

+0

非常有用。使用此功能创建基于句柄的片段路由系统 – Leland

0

@vovafeldman不知道为什么你不能有一个空白的片段,但没有文件存在。

我能想到的唯一的其他选择是因为您使用BG流程来生成代码段(并且我假设上传代码段),您可以随时使用模板API上传包含片段的模板版本与此同时。

2

扩展Jon的答案;

创建一个名为snippet.liquid

{% capture snippet_content %}{% include snippet %}{% endcapture %} 
{% unless snippet_content contains "Liquid error" %} 
    {{ snippet_content }} 
{% endunless %} 

然后,当你想包括一个文件只如果它存在

{% include 'snippet' with 'filename_of_include' %} 
+0

非常整齐的实施。 – Carlton