Shopify: Default Snippets

On occasion, a requirement will come down from a client where a portion of each page must be related to the content that is showing on the page. In this case, content is defined as a Collection, Product, the Cart. really anything in Shopify that has a handle that will not be changing.

In this case, let's say the sidebar has a whole set of links and images that need to render in a specific location, and those links will be 100% different for every page in the site.

The solution is really quite simple...

For this example, let's look at collection handles as our content key. We'll want to come up with a naming convention for our snippets. Let's do the following:


Important to note here is that handle is the actual handle of the collection the user is viewing. While we're at it, let's go ahead and define a default snippet for those cases where handle doesn't match the name of a defined snippet liquid file.


Now let's render these snippets where they belong. First, start in your collection.liquid file. You have to actually define the name of the snippet you're looking for in a variable to use it in an include statement. So to do that, write the following:

{% assign snippet_link = 'snippet-related-collection-' | append: collection.handle %}

Next, attempt to load it into memory. This is important because your client might add a new collection in the future and you don't want to show a liquid error on the page because the file they're trying to load doesn't exist.

{% capture snippet_content %}{% include snippet_link %}{% endcapture %}

Now the fun part... Check the result to see if the file worked by checking for the Liquid error text.

{% if snippet_content contains "Liquid error" %}
{% include 'snippet-related-collection-default' %}
{% else %}
{{ snippet_content }}
{% endif %}

Now just make sure to create the actual snippets and you are all set to go. You have the ability to create a new snippet for each unique handle, or fall back to the default if the file doesn't exist.

Happy coding!

comments powered by Disqus