Shopify liquid: How can I conditionally include snippets in Shopify liquid?
Extending on Jon's answer;
Create a file called snippet.liquid
{% capture snippet_content %}{% include snippet %}{% endcapture %}
{% unless snippet_content contains "Liquid error" %}
{{ snippet_content }}
{% endunless %}
Then when you want to include a file only if it exists
{% include 'snippet' with 'filename_of_include' %}
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.
Okay, Coming here in 2021.
The include syntax is deprecated and infrequently used, also extending @a.wmly answer, this should be the latest syntax replacing include with render:
{% 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 %}
references for include vs render : https://shopify.dev/docs/themes/liquid/reference/tags/deprecated-tags#include