Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 15

Formatting Data with Liquid Filters

Recommended resources

Hello! Welcome back.

In our last lesson, we established the three pillars of Liquid: objects for output {{ }}, tags for logic {% %}, and filters for modifying output |. We saw how they work together and got a brief introduction to the money filter.

Today, we will perform a deep dive into that third pillar. Our goal is to apply common Liquid filters to format strings, numbers, and dates. Filters are the primary tool in Liquid for manipulating data for presentation. For someone with your JavaScript background, you can think of them as Liquid's built-in functions for data transformation—analogous to JavaScript's string methods like .toUpperCase(), the Math object, or date-formatting libraries.

By the end of this lesson, you'll be able to confidently use a variety of filters to format product titles, calculate discounts, display user-friendly dates, and much more.

What are Filters, Exactly?

Let's start with a formal definition. Filters are simple methods that modify the output of strings, numbers, objects, and variables. They are separated from the output variable by a pipe character | and can accept optional parameters.

Demystifying Liquid Filters: A Guide with Examples

The article "Demystifying Liquid Filters" provides a clear and concise overview of what filters are and their syntax. This will serve as our foundation for the lesson.

Please read the sections 'Understanding Filters' and 'Filter Syntax'. This will formalize the concepts we're discussing.

As the article mentions, the syntax is straightforward: {{ output_expression | filter_name: parameter1, parameter2 }}.

You can also chain filters together, applying them from left to right. For example: {{ ' my string ' | strip | upcase }} would first remove whitespace, then convert the result to uppercase.

Let's watch a very quick visual recap of this concept.

Understanding Shopify Liquid

This short clip from Coding with Jan's "Understanding Shopify Liquid" video will reinforce the syntax and purpose of a filter.

Watch the segment from 03:24 to 04:41. It provides a simple, clear example of applying a filter to a variable.

Now, let's explore the most common filters, organized by the type of data they manipulate.


1. String Filters

String filters are essential for formatting text content like product titles, descriptions, and vendor names.

Demystifying Liquid Filters: A Guide with Examples

The "Demystifying Liquid Filters" article we looked at earlier has excellent, practical examples for common string and array-to-string operations.

Please review the following examples from the article: Example 1: Capitalizing a Product Title (Note: the text mistakenly says upcase, but the code correctly shows capitalize). Example 2: Truncating Product Descriptions, which demonstrates truncatewords. Example 6: Array Manipulation, which shows how to use join to convert an array of tags into a single string.

Let's consolidate what you've just seen with a few key categories of string filters:

  • Case formatting:
    • upcase: Converts a string to uppercase. {{ 'Hello' | upcase }} → HELLO
    • downcase: Converts a string to lowercase. {{ 'Hello' | downcase }} → hello
    • capitalize: Capitalizes the first word of a string. {{ 'hello world' | capitalize }} → Hello world
  • Whitespace control:
    • strip: Removes all leading and trailing whitespace.
    • lstrip: Removes leading (left) whitespace.
    • rstrip: Removes trailing (right) whitespace.
  • Truncation:
    • truncate: n: Truncates a string to n characters, appending an ellipsis (...).
    • truncatewords: n: Truncates a string to n words, appending an ellipsis.
  • Array/String Conversion:
    • split: 'delimiter': Splits a string into an array of substrings.
    • join: 'delimiter': Joins the elements of an array with the delimiter. This is extremely useful for displaying product tags, as seen in the article.

Another crucial filter is strip_html, which removes all HTML tags from a string. This is useful when you want to show a plain-text preview of rich text content, like a product description.

Test your understanding!

A product title is stored as " my awesome t-shirt ". You want to display it on the storefront as a heading that reads: SALE: MY AWESOME T-SHIRT.

Write the Liquid code to achieve this.

Show answer
{% assign product_title = "  my awesome t-shirt  " %}
<h1>{{ product_title | strip | upcase | prepend: 'SALE: ' }}</h1>

Explanation:

  1. strip removes the leading and trailing whitespace.
  2. upcase converts the string to uppercase.
  3. prepend: 'SALE: ' adds the specified text to the beginning of the string. The filters are applied sequentially from left to right.

2. Number (Math) Filters

In e-commerce, you're constantly dealing with numbers: prices, quantities, weights, and discounts. Liquid's math filters allow you to perform calculations directly in your templates.

How to Use Math Filters with Liquid

The Shopify Partners blog post "How to Use Math Filters with Liquid" provides an excellent real-world scenario: calculating the percentage saved on a sale item. This demonstrates the power of chaining multiple math filters.

Please read the sections 'Math filter basics' and 'Stringing along multiple math filters'. Pay close attention to how the example builds a complex calculation step-by-step to determine a percentage discount. This is a very common task in theme development.

As that article demonstrated, you can achieve powerful results by combining a few simple filters. The core math filters are:

  • plus: number: Adds a number. {{ 4 | plus: 2 }} → 6
  • minus: number: Subtracts a number. {{ 4 | minus: 2 }} → 2
  • times: number: Multiplies by a number. {{ 4 | times: 2 }} → 8
  • divided_by: number: Divides by a number. {{ 4 | divided_by: 2 }} → 2
  • modulo: number: Returns the remainder of a division. {{ 5 | modulo: 2 }} → 1

And for rounding:

  • round: Rounds to the nearest integer. {{ 4.6 | round }} → 5
  • ceil: Rounds up to the nearest integer. {{ 4.2 | ceil }} → 5
  • floor: Rounds down to the nearest integer. {{ 4.8 | floor }} → 4

The "percentage saved" example is a perfect illustration of how these work together:

{{ product.compare_at_price | minus: product.price | times: 100.0 | divided_by: product.compare_at_price | round }}

This chain logically performs the calculation round(((compare_price - price) * 100.0) / compare_price).


3. Date Filters

Displaying dates in a consistent, human-readable format is key to a professional-looking storefront. The date filter is your primary tool for this.

Demystifying Liquid Filters: A Guide with Examples

Let's revisit the "Demystifying Liquid Filters" article for its straightforward example on formatting dates.

Review Example 4: Formatting Dates and Times. Notice how a parameter is passed to the date filter to specify the exact output format.

The date filter takes a format string as a parameter. This string uses characters prefixed with % to represent different parts of a date. Here are some of the most common format parameters:

  • %Y: Year with century (e.g., 2023)
  • %m: Month of the year (01-12)
  • %d: Day of the month (01-31)
  • %B: The full month name (e.g., "January")
  • %b: The abbreviated month name (e.g., "Jan")
  • %A: The full weekday name (e.g., "Sunday")
  • %a: The abbreviated weekday name (e.g., "Sun")

You can combine these with other characters to create any format you need.

Example:
If article.published_at contains a full timestamp, you can format it like this:

{{ article.published_at | date: "%B %d, %Y" }} → January 25, 2024

Test your understanding!

A Shopify object order.created_at has the value 2024-07-15T14:30:00Z. You need to display this to the customer as "Mon, 15 Jul".

Which date filter and format string would you use?

Show answer
{{ order.created_at | date: "%a, %d %b" }}

Explanation:

  • %a gives the abbreviated weekday name ("Mon").
  • %d gives the day of the month ("15").
  • %b gives the abbreviated month name ("Jul").

Conclusion

Today we took a practical tour of Liquid's most common filters. You now have the tools to take raw data from Shopify and transform it into well-formatted, presentable information for the storefront.

Key Takeaways:

  • Filters modify output using the pipe | syntax and can be chained together.
  • String filters (upcase, truncate, strip, join) are your go-to for formatting textual content.
  • Math filters (plus, minus, times, divided_by, round) are essential for price calculations and implementing e-commerce logic.
  • The date filter provides powerful and flexible control over how timestamps are displayed to the user.

In our next lesson, we will zoom out from the code itself and look at the bigger picture. Now that you understand the building blocks of a template—objects, tags, and filters—we'll explore how they are organized within a Shopify theme's directory structure. This will set the stage for you to start building and modifying theme files.