Tips for Using Snippets in Your Shopify Theme Work

shopify snippets

Editor’s note: This article was first published in 2016. We have updated it to be current as of December 2020.includeis now deprecated. For more information on using therenderfunction instead, please visit thehelp center.

If you have worked with server-side languages you will already be familiar with the concept ofpartials orincludes. In Shopify,partials andincludes are known as snippets. To help you understand how Shopify uses them, here's a brief overview:

  • Snippets are files containing chunks of reusable code
  • They reside in the snippets folder
  • They have the.liquidextension
  • They are most often used for code that appears on more than one page but not across the entire theme
  • Snippets are included in a template using the Liquid tagrender, e.g.,{% render 'snippet name' %}
  • You do not need to append the.liquidextension when referencing the snippet name
  • When a snippet is included it will have access to the variables within its parent template
  • Examples of snippets include social links and pagination blocks

In this article, we’ll go over some tips for using Shopify snippets in your work.

Template Icon

Advanced snippet use

Snippets are extremely useful and allow you to keep repeated code in a single file. Above all, this has the benefit of enabling us to update all instances of that code from one file.

We use snippets a lot when designing themes. The main benefit we find is that they allow us to concentrate on discrete chunks of code, as opposed to dealing with long files. It also makes incorporating and working withShopify sectionsmuch easier. Given that there’s no performance disadvantage, we find that it’s just a nice way of working.

Of course, everyone has a different workflow style. But beyond the aesthetic and organizational benefits of snippets, there are other reasons that you might want to consider using them.

You might also like:如何Do an In-Depth Liquid Render Analysis with Shopify Theme Inspector.

Conditional loading of snippets

One example of an alternative use of a snippet is conditional loading. For example, let’s say we wanted to show a special offer box for a set of particular products, each of which has “coffee cup” in their product handle.

Every object within Shopify has a unique “handle”. In other platforms, such as WordPress, this is known as a “slug”. A handle is a URL-safe representation of an object. Every product has a handle that is automatically created based on the product title, but you have the potential to manipulate the handle in the admin to be whatever you like.

Given their unique nature, handles are easy to use in Shopify templates for comparison. By using a simple Liquidifstatement, we can check for the current product’s handle and make a decision on whether to include the snippet or not.

Here’s an example to explain the concept that would be placed inproduct.liquid:

{% if product.handle contains "coffee-cup" %}
{% render 'special-offer' %}
{% endif %}

As you can see, thisifstatement checks for the currently viewed product’s handle. If the returned value containscoffee-cupthen the template will include the snippetspecial-offer. If the returned value doesn’t match, the template will simply carry on rendering.

This is a very simplistic example of conditional loading, but it shows how we can use the power of Liquid in order to output different markup dependent on the product. By using this simple method, you can create exceedingly flexible themes.

Naming conventions

As mentioned earlier, the snippets folder acts as one big bucket for all of your client’s theme’s snippet files. As a result, we tend to prefix files with their function to make working with them cleaner and easier.

For example:

  • product-limited-edition-coffee-cup.liquid
  • product-showcase.liquid
  • collections-coffee-cups.liquid

You’ll notice that these are very much in line with the template naming conventions, making them much easier to integrate into your workflow.

Variable scope

When a snippet is rendered in a template file, the code inside it does not automatically have access to the variables assigned using variable tags within the snippet’s parent template. Similarly, variables assigned within the snippet can’t be accessed by the code outside of the snippet.

However, what if we’d like to make use of a snippet, and reference a variable that is a template variable? In order to achieve this, we simply use the Liquid tag{% assign %}and list the variables as parameters on the render tag.

Here’s an example:

{% assign my_variable = 'apples' %}
{% render 'name', my_variable: my_variable, my_other_variable: 'oranges' %}

The snippet will now have access to both the apples variable and the oranges variable. We could also make a Liquid collection available in the following format:

{% assign all_products = collections.all.products %} {% render 'snippet', products: all_products %}

It's also worth noting here that assigning a variable within the snippet that is also assigned in the parent template does not overwrite its value in the parent template.

You might also like:The Essential List of Resources for Shopify Theme Development.

Usingwith

To round out our look at snippets, let's spend some time looking at an example that uses the render tag parameterwith. This approach really shows off the power of snippets and allows us to create reusable code that can be used in a variety of applications.

To set the scene, let’s say we have a snippet that allows us to output a product collection in a template. Here’s a very basic example that we could save ascollection-product-list.liquid:

Since thecollectionsvariable is global, this will work as intended in any template. This snippet simply outputs an unordered list of links to every product in the store.

What if we wanted to make it possible to work with any individual product collection? In order to achieve this, we need to refactor the snippet to:

You’ll notice that instead of looping over every item in thecollections.all.productsLiquid collection, we have a placeholder variable that has the same name as our snippet minus the.liquidextension.

Let’s have a look at how we make use of this more generic snippet:

{% assign c = collections.all.products %}
{% render 'collection-product-list' with c %}

Firstly, we are assigning thecollections.all.productsto a Liquid variable. In this instance, it’s calledcbut can be named however you see fit.

Next we move onto therendertag and reference the snippet without the.liquidextension and follow it withc. Thewithparameter assigns a value to a variable inside a snippet that shares the same name as the snippet. Whilst this might sound confusing at first, have a quick look at the example above which has the following line in:

{% for product in collection-product-list %}

Effectively what is happening is that the variablecis referenced within the snippet bycollection-product-list. As such, our snippet will now function with any product collection we pass in using thewithparameter.

You might also like:如何Build for Modern Browsers (With Legacy Browser Support).

Extending our generic snippet

It’s also possible to pass in more than one variable to our snippet. A good example of this might be the number of products to show. We can achieve this in our snippet by using a limit clause on theforloop.

Here’s the refactored snippet:

And here’s how we would pass in a value for our limit clause to reference:

{% assign c = collections.all.products %}
{% render 'collection-product-list' with c, limit_count: 2 %}

When the snippet is rendered it will exit after the second loop. This makes our snippet even more generic and will allow us to use it in a variety of situations.

Note that omitting this variable will mean all the items in the Liquid collection are iterated over. Also if thelimit_countis higher than the number of items in the list, it will exit theforloop after the final list item.

你可以通过进一步comma-separat变量ing them after thewithparameter. For example, you could write:

{% render 'collection-product-list' with c, limit_count: 2, heading_text: 'All Products' %}

You can output theheading_textwithin the snippet in the following way:

{{ heading_text }}

Start using snippets today

While snippets might at first seem to be just another simple tool in your arsenal, it’s possible to turn them into a very powerful part of your theme development work that allows you to create reusable markup that you can use in a variety of applications.

Topics:

Grow your business with the Shopify Partner Program

Learn more