Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 61 ยท Liquid Basics

Filters: Strings, Math, Arrays

Learn Shopify Liquid filters: chaining, string filters like truncate and replace, math with plus, times and round, array filters like map, where and sort, default and escape.

Objects give you raw data: a product title in mixed case, a price in cents, a list of tags. Templates rarely print raw data. You shorten a title, turn cents into a decimal, pick only the available products, or join tags with commas. In Liquid you do this with filters: small functions that take a value, transform it, and hand the result on.

This lesson covers the filters you will use every day: string, math and array filters, plus default and escape. Shopify adds its own filters for money, images and URLs; those are in Shopify Filters: Money, Images, URLs and Assets. The standard filters below work in all current Online Store 2.0 themes, and Liquid is not tied to an Admin API version.

Shopify renders Liquid on its servers, so the theme snippets here are read-only. The runnable examples re-implement the filters in JavaScript so you can see what each one does. The behaviour follows Liquid, but the code is a stand-in, not Shopify's implementation.

How filters work

A filter goes after the value, separated by a pipe |. Some filters take arguments after a colon, separated by commas.

LIQUID
{{ product.title | upcase }}
{{ product.title | truncate: 20 }}
{{ product.title | truncate: 20, 'โ€ฆ' }}
{{ product.title | replace: 'Jacket', 'Coat' }}

You can chain as many filters as you like. They run from left to right, and each one receives the result of the previous one. Order matters:

LIQUID
{{ '  Trail Jacket  ' | strip | downcase | handleize }}
flowchart LR
    V["'  Trail Jacket  '"] --> F1["strip"]
    F1 --> F2["downcase"]
    F2 --> F3["handleize"]
    F3 --> O["'trail-jacket'"]

A chain passes the output of each filter into the next one.

Filter arguments can be literals ('text', 20) or variables (limit). An argument cannot itself contain a filter, so compute it first with assign. If a filter name is misspelled or does not exist, Theme Check reports it, so run it often (see Theme Check, Linting and Testing).

String filters

Filter What it does Example result
upcase, downcase change case TRAIL JACKET
capitalize first letter up, the rest down Red shirt
strip trim whitespace at both ends
append, prepend add text after or before card card--sale
replace, replace_first, remove replace or delete text red shirt large
truncate: n cut to n characters, including the ellipsis ... Free shipping on orde...
truncatewords: n cut to n words Lightweight, packable and warm...
split: ',' string to array ['new','sale']
size length of a string or array 12
handleize make a URL-style handle trail-jacket-men
strip_html, newline_to_br clean or convert text
url_encode, escape encode for URLs or HTML <b>

truncate is easy to misread. The number is the maximum length of the result, so with the default ... ellipsis, truncate: 24 keeps 21 characters of your text. Pass '' as the second argument for a hard cut with no dots. truncate cuts anywhere, even mid-word; truncatewords is friendlier for sentences.

Math filters

Filter Example Result
plus, minus 5 | plus: 3 8
times 10 | times: 1.25 12.5
divided_by 7 | divided_by: 2 3
modulo 7 | modulo: 3 1
round, ceil, floor 3.14159 | round: 2 3.14
abs -4 | abs 4
at_least, at_most 150 | at_most: 100 100

Two rules cause most of the bugs:

  1. Integer in, integer out. divided_by does integer division when both numbers are integers: 7 | divided_by: 2 is 3, not 3.5. Make either side a decimal to get a decimal result: 7 | divided_by: 2.0 gives 3.5.
  2. Prices are in cents. In Liquid, product.price is an integer in the smallest currency unit, so 12900 means 129.00. To calculate with it, stay in cents (times: 80 | divided_by: 100 for a 20 percent discount), and format at the very end with the money filter. Dividing by 100.0 and printing yourself skips currency formatting and the store's rules.

Numbers stored as strings are converted for math filters: '4' | plus: 3 is 7. Comparisons do not convert, as you saw in Conditions.

Try it: string and math filters

The editor contains re-implemented filters and a runner that applies a chain to a value and prints every step. Edit the chains at the bottom, or add your own, and run it again.

JS String and math filters step by step

Press Run (or Ctrl + Enter) to see the console output here.

No output.

What is real and what is not? The filter names, argument meaning and results match Liquid for these examples. The runner, the argument parser and the step printing are our own. One honest limit: JavaScript cannot tell 100 from 100.0, so the stand-in cannot show Liquid's float output (for example 129.0) and only demonstrates integer division and a decimal divisor.

Array filters

Arrays come from objects (product.tags, collection.products, cart.items) or from split. Array filters let you reshape them without a loop:

Filter What it does
map: 'title' pick one property from every item
where: 'available' keep items where the property is truthy
where: 'type', 'Jackets' keep items where the property equals the value
sort, sort: 'price' sort, by value or by property (case sensitive)
sort_natural sort ignoring case
reverse, uniq, compact reverse, remove duplicates, remove nil
first, last, size pick the ends, count
join: ', ' array to string
concat: other join two arrays into a new one
slice: 0, 2 take a part of an array or string
sum: 'price' add up a property

Chains of array filters replace a lot of loop-and-condition code:

LIQUID
{% assign jackets = collection.products | where: 'type', 'Jackets' | sort: 'price' %}
{{ jackets | map: 'title' | join: ', ' }}

Sorting with a property puts items with a missing value (nil) last, and uniq keeps nil as a value unless you call compact first; the next example shows both. If you only need a few items, a for loop with limit can still be the right tool; for a big list do not call several heavy filters over and over (see Liquid Performance).

JS Array filters over a product list

Press Run (or Ctrl + Enter) to see the console output here.

No output.

As before, the chain results are what Liquid gives for this data. The runner and the data objects are stand-ins; real collection.products objects have many more fields.

default and escape

Two filters protect your page from missing and unsafe values:

LIQUID
{{ product.metafields.custom.subtitle | default: 'No subtitle' }}
<h2>{{ section.settings.heading | escape }}</h2>
<a href="/search?q={{ search.terms | url_encode }}">โ€ฆ</a>
  • default replaces nil, false and empty values with a fallback. To keep a real false, use default: true, allow_false: true.
  • escape converts &, <, > and quotes into HTML entities. Liquid does not escape output automatically, so text that a merchant or customer typed should pass through escape (or be placed in a context that is safe). More in Security in Themes.

Common mistakes

  • Chain order. truncate: 20 | upcase and upcase | truncate: 20 give the same text here, but escape | truncate: 20 can cut an entity such as &amp; in half. Escape last.
  • Dividing cents by 100 and calling it money. Use the money filter for display.
  • Forgetting that filters return new values. {{ title | upcase }} does not change title. Use assign to keep the result.
  • Using filters to sort huge lists on every page view. Do heavy work once, or avoid it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does {{ 7 | divided_by: 2 }} print?

    When both numbers are integers, divided_by does integer division and drops the remainder. Use 2.0 as the divisor to get 3.5.
  2. 2. In what order does {{ name | strip | upcase | truncate: 8 }} run its filters?

    Filters form a pipeline. The first one gets the object value and every following filter gets the output of the filter before it.
  3. 3. You want only the available products, sorted by price. Which chain is right?

    Both orders return the same products. Filtering first is usually cheaper because you sort fewer items, but each chain is valid Liquid.
  4. 4. What does {{ 'Free shipping on all orders' | truncate: 12 }} print?

    The number is the maximum length of the result including the three-character ellipsis, so nine characters of the text are kept: Free ship plus ...

Summary

  • A filter transforms a value; chains run left to right and each filter gets the previous result.
  • String filters shape text (truncate, replace, split, handleize); truncate: n counts the ellipsis.
  • Math filters follow integer rules (7 | divided_by: 2 is 3), and prices are in cents until the money filter formats them.
  • Array filters (map, where, sort, uniq, compact, join, concat, slice, sum) replace many loops.
  • default supplies fallbacks and escape makes text safe for HTML; filters never change the original variable.

Next: Shopify Filters: Money, Images, URLs and Assets