Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 61 ยท Liquid Basics

Liquid Pitfalls and Debugging

Avoid the Liquid bugs that bite every Shopify theme developer: truthiness, blank versus empty, string versus number, scope leaks, array building, slow loops and how to debug.

Liquid looks simple, and that is exactly why it surprises people. It is a small, forgiving language: a typo does not crash the page, a missing variable prints nothing, and an if happily accepts almost any value. The result is a long list of bugs that do not announce themselves. A section that renders an empty <div> on one product, a price that is off by a factor of one hundred, a condition that is always true. This lesson collects the pitfalls that cause most of those bugs, and the habits that find them quickly.

What this lesson targets: current Shopify Liquid in Online Store 2.0 themes. The real Liquid rules are described in prose and read-only code blocks. The editors run a small Liquid-style engine written in JavaScript so you can watch the rules happen; it is a stand-in that copies the behaviors described here, not Shopify's implementation, and its error messages are modeled on Shopify's rather than guaranteed to match them word for word.

Truthiness: only nil and false are falsy

In many languages 0, the empty string and an empty list count as false. Liquid does not do that. In an if, exactly two values are falsy: nil (nothing, "no such thing") and false. Everything else is truthy, including 0, "" and an empty array.

flowchart TD
  A["Value in an if"] --> B{"nil or false?"}
  B -->|yes| C["falsy: the branch is skipped"]
  B -->|no| D["truthy: the branch runs<br/>even for 0, empty string, empty array"]

The whole truthiness rule of Liquid fits in one decision.

The most common casualty is a count:

LIQUID
{% if collection.products.size %}
  <p>This always runs, because 0 is truthy.</p>
{% endif %}

Write the comparison you mean instead: {% if collection.products.size > 0 %}, or better, {% if collection.products != empty %}.

nil, blank and empty

Liquid gives you two special words for the "nothing useful here" cases, and they are not the same:

Value == nil == empty == blank
nil (unset, missing) true false true
false false false true
"" (empty string) false true true
" " (spaces only) false false true
[] (empty array) false true true
0 false false false

empty means "has zero length" and works on strings, arrays and hashes. blank is broader: it also matches nil, false and strings that contain only whitespace. For text a merchant types into the theme editor, != blank is almost always the check you want, because a field cleared with the space bar should count as empty.

LIQUID
{% if section.settings.heading != blank %}
  <h2>{{ section.settings.heading | escape }}</h2>
{% endif %}

Note what a missing metafield or setting gives you: nil. Reading a property of nil gives nil again with no error, so product.metafields.custom.subtitle.value is safe even when the metafield does not exist.

Strings are not numbers

Liquid is strictly typed when it compares. "5" == 5 is false because one side is a string and the other a number. This bites where values arrive as text: a text setting that holds 3 is the string "3", while a range setting holds the number 3. A select setting returns the string of the option's value.

LIQUID
{% if section.settings.columns == 3 %}
  <p>False when columns is a text setting.</p>
{% endif %}

Ordering comparisons are stricter still. "5" > 3 is a Liquid error (a message such as "comparison of String with 3 failed" appears where the tag was), whereas comparing nil with a number simply gives false. Convert explicitly when you must: the math filters accept numeric strings, so "5" | plus: 0 yields the number 5.

The filters that look alike behave differently. "5" | plus: 3 is the number 8, but "5" | append: 3 is the string 53.

Money is in cents, and integers divide as integers

Shopify prices such as product.price are integers in the smallest currency unit (cents). 1999 means 19.99. Two traps follow. First, {{ 1999 | divided_by: 100 }} is 19, because dividing an integer by an integer gives an integer. Dividing by a float, 100.0, gives 19.99. Second, you almost never need to divide at all, since the money filter turns cents into a formatted price using the store's currency settings (Shopify Filters).

and/or have no precedence

Liquid has no parentheses in conditions and evaluates and/or chains from right to left. So a or b and c means a or (b and c), which differs from what many languages do. When a condition mixes both, split it into separate if tags or assign intermediate results to variables.

Scope leaks

Liquid has no block scope. A variable created with assign or capture stays alive for the rest of the file, even when it was created inside an if or a for. Only the loop variable (and forloop) disappear when the loop ends.

That has two effects. A flag you set in the first iteration of a loop is still set in the second, so reset it at the top of the loop body if you need a per-item value. And a variable assigned in a branch that never ran simply does not exist afterwards; reading it gives nil, which prints nothing and raises no error, so a typo hides just as quietly.

Between files the rule is the opposite and stricter: a snippet rendered with render cannot see or change your variables (render lesson). Inside one file, though, assume everything you assign is global to that file.

Building arrays and objects

Liquid has no array literal and no hash literal. You cannot write [1, 2, 3]. The usual workarounds all go through split:

LIQUID
{% assign sizes = 's,m,l' | split: ',' %}
{% assign list = '' | split: ',' %}
{% assign extra = 'xl' | split: ',' %}
{% assign list = list | concat: extra %}

The first line creates a three-item array from a string. The second creates an empty array, which you can grow with concat (joining arrays). Keep this in mind when reading old themes: you will see split used as an "array constructor" everywhere. You can also read with a variable key using brackets, which is how you reach a setting whose name is computed: section.settings[setting_key].

The editors: a pitfalls lab

Everything above in one place. The first editor contains the stand-in engine and runs the cases from this lesson. Read the output against the rules.

JS A Liquid pitfalls lab

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

No output.

Debugging in practice

When a section misbehaves, work from the outside in.

  1. Dump the value with json. {{ product | json }} prints a Liquid object as JSON. Put it in a <pre> and you see which properties exist, what type they are (a quoted "5" is a string, a bare 5 is a number) and whether the value is null. Wrap the dump so visitors never see it: {% if request.design_mode %}<pre>{{ variable | json }}</pre>{% endif %}. The design_mode flag is true inside the theme editor.
  2. Print the type. Check with == blank and == empty, or print a value between brackets so a stray space is visible: [{{ value }}].
  3. Comment out half. Liquid errors appear inline in the page ("Liquid error (sections/featured line 14): ..."), so look in the rendered HTML, not just on screen. Wrap code in {% comment %} to bisect the template.
  4. Run Theme Check. shopify theme check (or the editor extension) reads your Liquid statically and flags the quiet mistakes: variables and objects that are never defined, assigns that are never used, deprecated tags like include, missing snippet files and syntax errors. Rules such as UndefinedObject and UnusedAssign catch most typos before they reach a store (Theme Check lesson).
flowchart LR
  A["Wrong output"] --> B["Dump with json"]
  B --> C{"Value and type<br/>as expected?"}
  C -->|no| D["Fix the source:<br/>setting, metafield, argument"]
  C -->|yes| E["Check the condition<br/>nil, blank, string vs number"]
  E --> F["Run Theme Check"]

Check the data first, then the condition, then let the linter look for what you missed.

The second editor is a miniature version of what Theme Check's UndefinedObject and UnusedAssign rules do. It reads a template, collects every name that gets defined and every name that gets used, and reports the differences, with a "did you mean" hint for typos. The real tool is far more thorough; this one only handles the tags in the sample.

JS A mini undefined-variable linter

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

No output.

Loops cost more than they look

Liquid renders on Shopify's servers for every uncached request, so slow Liquid is slow time-to-first-byte for the shopper. A few habits matter most:

  • Cap loops. Use limit, or paginate, whenever the list can grow. A nested loop multiplies: 50 products times 20 variants times 10 metafield lookups is 10,000 operations for one page.
  • Do the work once. Compute a value before the loop and reuse it. A filter inside the loop body that gives the same answer on every pass is wasted work.
  • Be careful with all_products. Looking products up by handle through all_products['handle'] is limited per page (the documented limit was 20 lookups at the time of writing; check the docs), so it is for a handful of featured items, not for building a catalog.
  • Break early. break stops a loop when you have what you need.

The dedicated lesson on Liquid Performance goes deeper into measuring this with Shopify's theme profiler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does {% if cart.item_count %} do when the cart is empty (item_count is 0)?

    In Liquid only nil and false are falsy. Write the comparison you mean, for example cart.item_count > 0 or cart != empty.
  2. 2. A merchant clears a heading field but leaves a single space in it. Which check treats it as empty?

    blank matches nil, false, empty and whitespace-only strings. empty only matches zero-length strings and arrays, and a plain if treats any string as truthy.
  3. 3. What does {{ 1999 | divided_by: 100 }} print?

    Dividing an integer by an integer is integer division. Use 100.0 for a decimal result, or better, the money filter.
  4. 4. A text setting holds the value 3. What does {% if section.settings.columns == 3 %} evaluate to?

    Equality is strict across string and number. Use a range setting for numbers, or compare with the string "3".
  5. 5. Where does a variable created with assign inside an if tag live?

    assign and capture are file-wide. Only a for loop's own variable and forloop disappear when the loop ends.

Summary

  • Only nil and false are falsy. 0, "" and empty arrays are truthy, so compare explicitly (size > 0, != empty).
  • empty means zero length; blank also covers nil, false and whitespace-only strings. Use != blank for text from the editor.
  • Strings and numbers never compare equal, and ordering a string against a number is an error. Check which setting type or metafield type you have.
  • Prices are integers in cents; integer division truncates, so use the money filter instead of dividing.
  • and/or evaluate right to left with no parentheses; split complicated conditions.
  • assign and capture have no block scope. Build arrays with split and concat.
  • Debug with | json, hidden behind request.design_mode, and let Theme Check catch undefined and unused variables.
  • Cap loops and move repeated work out of them.

Next lesson: Layouts and theme.liquid.