Shopify Liquid Cheat Sheet
A Comprehensive Guide to Mastering Custom Code Snippets
Shopify has revolutionized the e-commerce world, making it easy for entrepreneurs and established businesses alike to create online stores and reach global audiences. One of the most powerful aspects of Shopify’s platform is its templating language, Liquid.
Originally developed by Shopify, Liquid is a robust, flexible language that allows developers and store owners to create highly customized experiences within their themes.
Liquid is the heartbeat of Shopify theme development. By mastering its fundamental concepts—objects, tags, and filters—you’re equipped to harness the power of dynamic data and create a truly personalized shopping experience. This guide has walked you through the essentials of Liquid syntax, provided examples of common use cases, and offered practical advice on building and maintaining custom code snippets.
Remember, the key to effectively using Liquid is striking the right balance between practicality and creativity. Don’t be afraid to experiment with new ideas or push the limits of what your store can do. With a solid grounding in Liquid, you have all the tools you need to transform your Shopify theme into a uniquely branded, highly optimized storefront that resonates with your customers.
Whether you’re just starting your Liquid journey or are already crafting intricate customizations, consider this cheat sheet an ongoing resource. Keep it handy to refresh your memory on syntax, logic, and best practices. As Shopify evolves, so will Liquid, and staying attuned to the latest developments will ensure you keep your store ahead of the curve.
Liquid Code & Shopify
Shopify has revolutionized the e-commerce world, making it easy for entrepreneurs and established businesses alike to create online stores and reach global audiences.
One of the most powerful aspects of Shopify’s platform is its templating language, Liquid. Originally developed by Shopify, Liquid is a robust, flexible language that allows developers and store owners to create highly customized experiences within their themes.
This “Shopify Liquid Cheat Sheet” blog post is designed to give you a thorough overview of how Liquid works, how you can use it to craft dynamic and personalized storefronts, and how you can integrate custom code snippets to take your Shopify store to the next level.
In this comprehensive guide, we will look into the fundamentals of Liquid, including its syntax, objects, tags, and filters. We’ll also delve deeper into some practical examples you can apply in your own Shopify environment.
By the end of this post, you should feel confident using Liquid to control your store’s design and functionality, tailoring it precisely to the unique needs of your business and customers.
Whether you are completely new to Liquid or seeking an in-depth refresher, this cheat sheet will be invaluable.
Let’s begin by exploring the essentials of Liquid and why it’s essential for unlocking the full potential of your Shopify store.
Understanding Liquid: The Basics
Liquid is a template language that acts as the backbone of all Shopify themes. It was created to enable developers to embed dynamic content in their storefront pages. Essentially, Liquid works behind the scenes to gather data from your Shopify store—such as products, collections, or customer information—and render that data seamlessly into your theme. The unique aspect of Liquid is that it runs on the server side. When a user visits a page on your store, Shopify processes your Liquid template files, merges them with the store data, and delivers pure HTML (and CSS/JavaScript) to the user’s browser. This approach helps maintain site performance while allowing you to craft sophisticated, data-driven user experiences.
Key Concepts in Liquid
Objects: Variables that hold information about your store or particular components (e.g., products, collections, carts).
Tags: Logic blocks (e.g., control flow, looping) and variable assignment.
Filters: Methods that transform Liquid objects and output the modified result.
Liquid syntax is contained within double curly braces {{ }} when displaying a value, or within curly-brace-percent {% %} tags when performing logic operations. For example:
Output:
{{ product.title }}displays the title of a product.Logic:
{% if product.available %} In Stock {% else %} Out of Stock {% endif %}uses control flow logic.
Together, these three building blocks—objects, tags, and filters—form the foundation for building dynamic Shopify themes. Let’s take a closer look.
Liquid Objects: Tapping Into Your Store’s Data
Objects in Liquid refer to the dynamic data you can access within your Shopify theme. These objects are generally represented by double curly braces{{ }}, which tells Liquid that you want to output a particular piece of data. For instance:
{{ shop.name }}
would display the name of your store. Similarly,
{{ product.title }}
displays the title of a product.
Some commonly used objects in Liquid include:
shop: Contains general store information (e.g., name, domain, currency).
product: Holds product-specific properties, such as
title,description,price, and more.collection: Provides details about a specific collection, like
title,description, andproducts.cart: Refers to the current user’s cart and contains properties like
item_count,total_price, anditems.customer: When a customer is logged in, you can use the
customerobject to access details such asfirst_name,last_name,email, and more.
By mastering these objects, you can dynamically render just about any piece of data within your Shopify store, from product titles and prices to collection descriptions. Here is a practical example of outputting product information:
{{ product.title }}
Price: {{ product.price | money }}
{{ product.description }}
In this snippet, we are using the product object to display its title, transform the raw product price into a formatted money representation via the money filter, and finally output the product’s description. This is the core of how you’ll often utilize Liquid to populate your theme with real store data..
Liquid Tags: Logic, Control Flow, and More
While objects let you pull data, tags in Liquid let you manipulate that data and control how it’s rendered. Tags are enclosed in curly-brace-percent blocks {% %}. The main categories of tags are:
Control Flow Tags: Includes
if,elsif,else,unless, andcase. These tags enable you to change the output of your templates based on certain conditions.Iteration Tags: Primarily
forloops, used to iterate over collections or lists of objects. There’s also thebreakandcontinuetags that affect loops’ behavior.Variable Assignment: Using the
assignorcapturetags to create your own variables.Include/Section Snippets: Incorporate partial templates or sections into your main template files.
Comment Tags: Allows you to insert comments in your code. These are not rendered in the final HTML output.
Control Flow Example
{% if product.available %}
This product is available to purchase.
{% else %}
Sorry, this product is out of stock.
{% endif %}
Here, if checks the product.available property. If the product is available, we show a message; otherwise, we display a different message.
Iteration Example
{% for item in cart.items %}
{{ item.title }} - {{ item.quantity }} x {{ item.price | money }}
{% endfor %}
This loop goes through each item in the cart and displays its title, quantity, and formatted price. for loops are particularly powerful because you can iterate over products, collections, line items in a cart, and more.
Variable Assignment Example
{% assign shipping_threshold = 50 %}
{% if cart.total_price > shipping_threshold %}
You qualify for free shipping!
{% else %}
Add more items to qualify for free shipping!
{% endif %}
In this snippet, we create a variable shipping_threshold with the value 50. We then use an if statement to check if the total cart price exceeds 50, and display a corresponding message.
Liquid Filters: Transforming Your Output
Filters are methods you apply to Liquid objects to change their output. Filters are added to a Liquid object using the pipe character |. For instance:
{{ product.title | upcase }}
would display the product’s title in uppercase letters. Filters let you format strings, numbers, arrays, and more. A few common filters include:
upcase/downcase: Converts a string to uppercase or lowercase.capitalize: Capitalizes the first letter of a string.money: Formats numbers as currency, based on your store’s currency settings.replace: Replaces a specified substring with another within a string.split: Splits a string into an array based on a delimiter.join: Joins an array’s elements into a single string, separated by a specified delimiter.truncate: Shortens a string to a certain number of characters, appending ellipses by default.date: Formats date strings into specific styles, like “September 21, 2025”.
Let’s look at a short example:
{{ product.title | downcase | replace: ' ', '-' }}
Here, the product title is converted to lowercase, and all spaces are replaced with dashes. This could be useful for generating a URL-friendly string (also known as a “slug”).
Putting It All Together: A Simple Example
Imagine you want to display a list of the first three products in a particular collection, showing their titles, images, and prices:
{% for product in collection.products limit:3 %}
{{ product.title }}
{{ product.price | money }}
{% endfor %}
Here’s what’s happening:
for product in collection.products limit:3: We loop through thecollection.productsarray, but only up to three items because of thelimit:3parameter.<img src="{{ product.featured_image | img_url: 'medium' }}" alt="{{ product.title }}">: We output the product’s featured image in a medium size.<h3>{{ product.title }}</h3>: We display the product title.<p>{{ product.price | money }}</p>: We display the product price formatted as currency.
Such a snippet is often found in a collection template or a homepage section that showcases top products.
The Anatomy of a Shopify Theme
Before diving further into custom snippets, it’s critical to understand how Shopify’s theme files are organized. A typical Shopify theme consists of:
Layout: Contains your master layout file (e.g.,
theme.liquid) which pulls together your header, footer, and main content.Templates: These are page- or resource-specific templates. Examples include
product.liquid,collection.liquid,index.liquid,cart.liquid, etc.Sections: Used in modern Shopify themes to create customizable sections that can be rearranged in the Theme Editor.
Snippets: Contain small reusable code blocks you can include across multiple templates. For instance, a snippet might handle product reviews or a unique promotional banner.
Assets: Where you store images, CSS, JavaScript, or any other static file needed for your theme.
Config: Houses your theme settings in
settings_schema.jsonorsettings_data.json.Locales: Contains translation files for multi-language support.
Liquid code is used in layout, template, section, and snippet files to bring dynamic data into the store’s HTML. Understanding the interplay among these files is key to effectively customizing your theme.
Creating Custom Code Snippets
One of the best ways to organize your custom Liquid code is by using snippets. Snippets are small, reusable sections of Liquid code that you can “include” in your main template files or sections. This is especially useful if you plan to reuse certain logic in multiple places throughout your theme.
Step-by-Step: How to Create and Use a Custom Snippet
Create a New Snippet: In your Shopify admin, navigate to “Online Store” > “Themes” > “Edit code.” Under the “Snippets” folder, click “Add a new snippet” and name it something descriptive, such as announcement-bar.liquid.
Write Your Liquid Code: Within your new snippet file, write the code you want to reuse. For example:
{{ announcement_text }}
You might have a variable announcement_text set within your theme settings or assigned in your layout file.
Include the Snippet: To use your snippet, open any Liquid file (e.g., the theme.liquid layout file) and add:
{% include 'announcement-bar' %}
The snippet name must match the file name. Shopify will then insert the contents of the snippet at that location in your code.
Add Additional Logic or Styling: You can enhance your snippet with Liquid logic or wrap it in custom classes/CSS to tailor its appearance and functionality. For instance:
{% if settings.announcement_enabled %}
{% include 'announcement-bar' %}
{% endif %}
In this scenario, the snippet only appears if an “announcement enabled” setting is toggled on in your theme settings.
By isolating repetitive code in snippets, you keep your theme files cleaner and maintain consistency across all pages. This also streamlines future updates. If you need to make a change to a snippet, you only have to do it once in the snippet file, rather than in multiple template files.
Tips for Using Custom Liquid Code Snippets
Name Snippets Clearly: For maintainability, give your snippets descriptive names. For example, use
product-card.liquidfor a snippet that outputs a product card layout, rather than something generic likesnippet1.liquid.Use Theme Settings Where Possible: If your snippet outputs text or images that you might want to tweak without touching code, consider hooking it up to theme settings. That way, store owners or other team members can modify the content through Shopify’s Theme Editor.
Be Mindful of Performance: While snippets are a great way to break your code into reusable pieces, don’t go overboard. Multiple includes can slow down theme compilation, so use them wisely, especially if they contain complex queries or logic. Always test your store’s load times after adding new snippets.
Scope Variables Appropriately: If you create custom variables inside a snippet, they remain in that snippet’s scope unless you pass them in or out explicitly. This can help avoid naming conflicts, but you also need to be mindful if you need a variable accessible outside the snippet.
Keep Logic Minimal Where Possible: Even though Liquid can handle a lot of logic, aim to keep your code as simple as possible. You should use tags and filters to shape your data, but if you find yourself writing complex logic, consider whether you can simplify your approach or break it down into smaller, more maintainable snippets.
Test Across Different Themes and Devices: Always check how your custom Liquid code appears on various devices and in different themes. Shopify merchants often swap themes over time; well-structured snippets are more likely to be portable or adaptable.
Advanced Liquid Techniques and Best Practices
Once you have a handle on the basics, you can explore more advanced Liquid features that can give your Shopify store a distinctive edge. Let’s highlight a few notable ones:
1. Liquid Objects for Internationalization (i18n)
Shopify supports multiple languages and locales through theme translations. You can access translations using Liquid’s t filter:
{{ 'general.newsletter_signup' | t }}
This filter pulls the translated string from your theme’s locales folder. This is especially helpful if you run a multilingual store or target different regions.
2. Using paginate for Collections
When you want to display a large collection of products, consider using Liquid’s pagination feature:
This snippet limits the number of products displayed per page and provides navigational links to move through the product listings.
3. Customizing Metaobjects
Shopify’s metafields and metaobjects let you store and retrieve custom data about products, collections, and other parts of your store. You can display these additional properties in your theme:
{% if product.metafields.custom.size_chart %}
View Size Chart
{% endif %}
By checking for the existence of product.metafields.custom.size_chart, you can conditionally render a link to a custom size chart PDF or page.
4. Liquid in JSON Templates
Modern Shopify themes often contain JSON templates (e.g., product.json, collection.json) to specify which sections are available on a given page. While Liquid is not as prominently used in JSON templates, you can still use some Liquid logic to provide dynamic values. For example:
{
"sections": {
"product-recommendations": {
"type": "product-recommendations",
"settings": {
"heading": "{{ 'products.recommended_title' | t }}"
}
}
}
}
This can be useful for pulling in translations or theme settings into your JSON-based layouts.
5. Optimizing Loops with limit, offset, and cols
When iterating over large collections, remember you can limit the number of items displayed and even skip the first few:
{% for article in blog.articles limit:5 offset:2 %}
{{ article.title }}
{% endfor %}
Here, we skip the first two articles in the blog and only show five articles afterward.
Troubleshooting Common Liquid Issues
As you explore Liquid, you may encounter some challenges. Here are a few common pitfalls and how to address them:
Syntax Errors: If you see an error like
Liquid error: Unknown tag '... 'orLiquid error: Unknown filter '...', double-check your syntax. Perhaps you spelled a filter name incorrectly or forgot a closing brace.Nil / Null Objects: Sometimes certain objects or properties might be
nil(i.e.,null). For instance, if you reference a metafield that doesn’t exist for a particular product, it might produce an error or fail silently. You can use conditional checks to prevent errors:
{% if product.metafields.custom.size_chart != nil %}
{% endif %}
{% for article in blog.articles limit:5 offset:2 %}
{{ article.title }}
{% endfor %}
Exceeding Theme Limits: Each theme has a limit on the number of sections, blocks, or snippet includes you can utilize. If you run into these limits, consider condensing your code or removing unnecessary includes.
Performance Concerns: Too many nested loops or complex if statements can bloat your theme, leading to slow page loads. Profile your code carefully. If certain data sets are massive, consider using pagination or alternative strategies.
Incorrect Variable Scope: If you’re setting a variable within a snippet and expecting to access it outside that snippet, it won’t work unless you pass it in or out properly. Liquid scoping rules can sometimes trip up new developers.
Practical Examples: Custom Liquid Code Snippets for Your Shopify Store
Below, we’ll walk through a few custom snippets you might find useful in your theme development.
Example 1: Dynamic Welcome Message
Create a snippet called welcome-message.liquid:
{% assign greeting = 'Hello' %}
{% if customer %}
{% assign greeting = greeting | append: ', ' | append: customer.first_name %}
{% endif %}
{{ greeting }}, welcome to our store!
In your layout file (theme.liquid), you’d include it like so:
{% include 'welcome-message' %}
Now, if a user is logged in, they’ll see “Hello, [First Name], welcome to our store!” If not, they’ll just see “Hello, welcome to our store!”
Example 2: Collection-Specific Banner
You can create a snippet called collection-banner.liquid:
{% if collection.metafields.custom.banner_image %}
{% else %}
{{ collection.title }}
{% endif %}
Include the snippet in collection.liquid:
{% include 'collection-banner' %}
If the collection has a custom banner image metafield, display it. Otherwise, display a fallback banner.
Example 3: Product Badge
If you have a snippet that dynamically displays a badge on products (e.g., “Sale,” “New Arrival,” or “Bestseller”), you can create something like:
{% comment %}
product-badge.liquid
Assign "badge_type" based on certain conditions
{% endcomment %}
{% assign badge_type = '' %}
{% if product.compare_at_price > product.price %}
{% assign badge_type = 'Sale' %}
{% elsif product.tags contains 'new' %}
{% assign badge_type = 'New Arrival' %}
{% elsif product.tags contains 'bestseller' %}
{% assign badge_type = 'Bestseller' %}
{% endif %}
{% if badge_type != '' %}
{{ badge_type }}
{% endif %}
In your product-card snippet or product template, you could do:
{% include 'product-badge' %}
This snippet checks whether the product is on sale, new, or a bestseller, and outputs the corresponding badge.
Best Practices for Maintaining Your Liquid Code
Comment Generously: Liquid templates can get complex quickly. Use the
{% comment %}tag to explain sections of your code so you and future collaborators understand the logic.Organize Your Snippets: Group similar snippets into subfolders or use consistent naming conventions (e.g.,
product-*,collection-*,header-*). Although Shopify doesn’t natively support subfolders within “Snippets,” you can emulate organizational patterns via naming.Keep Your Theme.liquid File Slim: Resist the urge to cram all logic into
theme.liquid. Instead, break it into snippets or sections to keep code clean and modular.Utilize Git or Version Control: If you’re working on a custom theme or implementing advanced features, consider syncing your Shopify theme with a Git repository. This ensures you can roll back changes if something breaks and keep track of who changed what.
Stay Updated: Shopify frequently updates the Liquid language and theme development best practices. Keep an eye on announcements and consider scanning official documentation periodically to learn about new features or deprecations.
Test on a Duplicate Theme: Always test new Liquid code on a duplicate of your live theme to avoid breaking your store’s user experience. Make changes, preview them, and then publish only when you’re confident everything works as intended.
Leveraging Liquid’s Power for Personalization
One of Liquid’s greatest strengths is the ability to tailor content to different user segments, making your store more engaging. For instance:
Logged-In vs. Guest Users: Display special discounts or messages to logged-in users. Offer an incentive to guest users to sign up for an account.
Customer Tags: If you tag customers based on loyalty status (e.g., “VIP”), you can use Liquid to display exclusive items or pricing tiers.
Geolocation: While you can’t directly detect geolocation in Liquid, you can store geolocation data as a metafield or pass it via an app, letting you show region-specific promotions or messages.
An example of personalization using customer tags:
{% if customer and customer.tags contains 'VIP' %}
Thank you for being one of our VIP customers!
Your exclusive discount code: VIPTHANKS
{% else %}
Join our VIP program to get exclusive discounts!
{% endif %}
This snippet allows you to craft special experiences for your most loyal customers without needing an external app or complex code.
The Future of Liquid: Ongoing Developments
Shopify continuously refines Liquid, expanding its capabilities to keep pace with evolving e-commerce trends.
Some of the more recent or upcoming enhancements might include better integration with new Shopify features (e.g., metaobjects), performance improvements, and expansions to the filter/tag library.
Keeping abreast of these changes will ensure you can take full advantage of new functionalities and continue pushing the boundaries of what’s possible in your store.
Call to Action
Schedule a consultation with the e-commerce team and Shopify developers of Empathy First Media to learn how our team can help you with e-commerce project needs.