Search code examples
apiincludecode-snippetsshopifyliquid

Shopify liquid: How can I conditionally include snippets in Shopify liquid?


I would like to include a snippet in a template but only if the snippet file exist. Is there any way I can do it?

Now I'm just using:

{% include 'snippetName' %}

But this throws the error:

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

The reason I need such a functionality is because I have a background process that adds the snippet later on.


Solution

  • Had this problem myself. This was my solution:

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

    Basically capture the snippet’s content as a variable. If there is no snippet Shopify generates the error:

    Liquid error: Could not find asset snippets/caroline-flint-reviews.liquid

    So check to see if it’s generated that… if so don’t print the snippet :D

    Of course this would break if you intended your snippet to include "Liquid error" or if Shopify ever change the error message.