【问题标题】:Shopify liquid: How can I conditionally include snippets in Shopify liquid?Shopify 液体:如何有条件地在 Shopify 液体中包含片段?
【发布时间】:2013-01-18 00:04:45
【问题描述】:

我想在模板中包含一个 sn-p,但前提是 sn-p 文件存在。有什么办法可以吗?

现在我只是在使用:

{% include 'snippetName' %}

但这会引发错误:

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

我需要这样一个功能的原因是因为我有一个后台进程,稍后会添加 sn-p。

【问题讨论】:

    标签: api include code-snippets shopify liquid


    【解决方案1】:

    我自己也遇到过这个问题。这是我的解决方案:

    {% capture the_snippet_content %}{% include the_snippet %}{% endcapture %}
    {% unless the_snippet_content contains "Liquid error" %}
      {% include reviews_snippet %}
    {% endunless %}
    

    基本上将 sn-p 的内容捕获为变量。 如果没有 sn -p Shopify 生成错误:

    液体错误:找不到资产 sn-ps/caroline-flint-reviews.liquid

    所以检查它是否生成...如果是这样,请不要打印 sn-p :D

    当然,如果您希望您的 sn-p 包含“液体错误”,或者如果 Shopify 曾经更改错误消息,这将会中断。

    【讨论】:

    • 非常有用。最终使用它来制作基于句柄的 sn-p 路由系统
    【解决方案2】:

    延续乔恩的回答;

    创建一个名为 sn-p.liquid 的文件

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

    那么当你想只包含一个存在的文件时

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

    【讨论】:

    • 非常简洁的实现。
    【解决方案3】:

    好的,2021 年来这里。

    include 语法已弃用且很少使用,也扩展了@a.wmly 答案,这应该是用渲染替换包含的最新语法:

    {% capture snippet_content %}{% render 'your-snippet-name' %}{% endcapture %}
    {% if snippet_content contains "Could not find asset" %}
        {% comment %} do nothing {% endcomment %}
    {% else %}
        {% render 'your-snippet-name' %}
    {% endif %}
    

    包含与渲染的参考:https://shopify.dev/docs/themes/liquid/reference/tags/deprecated-tags#include

    【讨论】:

      【解决方案4】:

      或者,您可以创建自己的标签,在尝试处理文件之前检查文件是否存在。

      https://github.com/Shopify/liquid/wiki/Liquid-for-Programmers#create-your-own-tags

      【讨论】:

      • 如果您从“根”管理您的液体,您可以创建自己的标签。 Shopify 已定义所有标签,您无法创建新标签。
      【解决方案5】:

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

      我能想到的唯一其他选择是,由于您使用 BG 进程来生成 sn-p(我假设上传它),您始终可以使用模板 API 上传包含同时sn-p。

      【讨论】:

        【解决方案6】:

        使用 Jon 或 a.wmly 上面列出的代码仍然给我错误。但是,简单地写

        {% include 'snippet_name' %}
        

        工作得很好。

        请注意,这只适用于位于“sn-ps/”文件夹中的文件。因此,例如,模板无法使用此方法工作。

        【讨论】:

          猜你喜欢
          • 2012-06-06
          • 1970-01-01
          • 2020-08-22
          • 1970-01-01
          • 1970-01-01
          • 2018-08-17
          • 2021-09-04
          • 2020-12-26
          • 1970-01-01
          相关资源
          最近更新 更多