Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 61 ยท Liquid Basics

Variables: assign, capture, increment

Learn how to create and use Shopify Liquid variables with assign, capture, increment and decrement, plus scope rules, naming, building strings and arrays, and defaults.

Theme code often needs a value more than once: a CSS class list that depends on three conditions, a price you calculate once and print twice, the first available variant found in a loop. Instead of repeating the expression, you store it in a variable. Liquid gives you four tags for this: assign, capture, increment and decrement.

The tags below behave the same in all current Online Store 2.0 themes, and Liquid is not tied to an Admin API version. You should already know output and objects, conditions and loops.

Shopify renders Liquid on its own servers, so theme snippets here are read-only. The runnable examples use a small Liquid-style engine written in JavaScript. It follows Liquid's rules for these tags, but it is a teaching stand-in, not Shopify's code.

assign: store a value

assign evaluates an expression and stores the result under a name. The expression can be a literal, an object property, or any of those followed by filters.

LIQUID
{% assign sale_price = product.price | times: 0.8 %}
{% assign heading = section.settings.heading | default: product.title %}
{% assign tags = 'new,sale,outdoor' | split: ',' %}
{% assign is_on_sale = false %}

Remember three points:

  • There are no operators in assign. {% assign total = price + 5 %} is not valid; write {% assign total = price | plus: 5 %}. Math lives in filters, which are the topic of Filters: Strings, Math, Arrays.
  • Types are kept. assign n = 5 stores a number, assign n = '5' stores a string, and the two are not equal in a comparison.
  • There is no array literal. You make arrays with split, filters such as where and map, or by reading one from an object. An empty array is usually written {% assign list = '' | split: ',' %}.

After the assignment you print or test the variable like any object: {{ sale_price }}, {% if is_on_sale %}.

Building strings and arrays step by step

A very common job is to build a class list from several conditions. Each assign replaces the previous value, so you pass the variable through a filter and store it back:

LIQUID
{% assign classes = 'card' %}
{% if product.compare_at_price > product.price %}
  {% assign classes = classes | append: ' card--sale' %}
{% endif %}
{% unless product.available %}
  {% assign classes = classes | append: ' card--sold-out' %}
{% endunless %}

<div class="{{ classes }}">โ€ฆ</div>

Arrays work the same way with concat, which joins two arrays and returns a new one. Because an array literal does not exist, small arrays are made by splitting a string, as the first runnable example shows. Liquid has no push: you always assign a new array.

flowchart LR
    A["classes = 'card'"] --> B{"On sale?"}
    B -- yes --> C["classes = classes + ' card--sale'"]
    B -- no --> D{"Sold out?"}
    C --> D
    D -- yes --> E["classes = classes + ' card--sold-out'"]
    D -- no --> F["Print classes"]
    E --> F

Each step reads the variable, changes it with a filter, and assigns it back.

capture: store rendered output

capture stores everything rendered between capture and endcapture as one string. It is the right tool when the value is built from several outputs, tags and text.

LIQUID
{% capture button_label %}
  {{ 'products.product.add_to_cart' | t }} ({{ product.price | money }})
{% endcapture %}

<button>{{ button_label }}</button>

Differences from assign worth remembering:

  • The result is always a string, even if the content looks like a number. {% capture n %}{{ 1 | plus: 1 }}{% endcapture %} makes the string "2". n == 2 is false, n == '2' is true, and n | plus: 1 works because the plus filter converts the string to a number.
  • Whitespace is kept. Use {%- capture x -%} and {%- endcapture -%} (whitespace control from Liquid Basics) if you do not want line breaks and spaces in the stored text.
  • Use assign when a single expression is enough. Use capture when you need tags (if, for) inside the value.

increment and decrement: counters

increment and decrement create a number that counts. Each time the tag runs it prints the current value, then changes it.

LIQUID
{% increment step %} {% increment step %} {% increment step %}

The output is 0 1 2. increment prints before adding, starting at 0. decrement subtracts first and then prints, starting at -1, so two decrement tags print -1 -2. A decrement and increment of the same name share one counter.

The key surprise: counters are independent from assign and capture variables. If you wrote {% assign step = 10 %} first, {{ step }} still prints 10 afterwards, even though {% increment step %} ran. The counter and the assigned variable live in different places. Because of that, most developers prefer forloop.index or an explicit assign with plus, which are easier to read. Use increment when you need a counter that keeps growing across several separate pieces of markup, for example unique id attributes in one rendering pass.

Scope: where variables live

Liquid has very simple scope rules, and they differ from most languages:

  • assign and capture variables are visible from the point where they are created until the end of the file being rendered. A variable assigned inside an if or a for is still there after the block ends.
  • The loop variable (product in for product in โ€ฆ) and the forloop object exist only inside the loop.
  • A snippet that you render with the render tag starts with an empty scope: it cannot see the caller's variables unless you pass them in, and what it assigns does not leak back out. The older include tag shared scope, which is one reason it is deprecated. See Snippets and the render Tag.
  • Sections are rendered separately. Do not count on a variable assigned in one section being available in another.

Run the example below and look at the last two result groups: last_seen survives the loop, while t does not.

JS Variable tags in a mini Liquid engine

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

No output.

What is real and what is not? The behaviour of assign, capture, increment/decrement and scope follows Liquid. The engine, the error handling and the handful of filters are simplified stand-ins.

Naming

Names may contain letters, digits and underscores (hyphens are allowed by the parser but make code harder to read). Good conventions:

  • Use snake_case, because Shopify's own objects and properties are snake_case.
  • Do not reuse the name of a global object. {% assign product = โ€ฆ %} replaces the real product for the rest of the file, and you will chase a confusing bug later.
  • Say what the value means: first_available_variant, not v or tmp.
  • Prefix booleans with is_ or has_: is_on_sale, has_media.

Default values

A variable that comes from a setting, metafield or optional argument may be nil or empty. The default filter supplies a fallback:

LIQUID
{{ product.metafields.custom.subtitle | default: 'No subtitle' }}
{% assign vendor_name = product.vendor | default: shop.name %}

default uses the fallback when the value is nil, false or empty (an empty string or empty array). Because false also triggers it, a setting that is deliberately false needs default: true, allow_false: true.

The second example is an ordinary JavaScript program: a naming linter for the rules above. Theme Check is the real linter for themes (more in Theme Check, Linting and Testing); the rules in this stand-in are our own.

JS A variable-name linter

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

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type does {% capture n %}{{ 1 | plus: 1 }}{% endcapture %} store in n?

    capture always stores a string. Comparing n == 2 is false; n == '2' is true.
  2. 2. You run {% assign step = 10 %} and then {% increment step %} three times. What does {{ step }} print afterwards?

    Counters made by increment live separately from assign variables. The assigned value 10 is what {{ step }} prints; the three increments printed 0, 1 and 2 as they ran.
  3. 3. Which line correctly adds 5 to a price?

    assign has no arithmetic operators. Math is done with filters such as plus, minus, times and divided_by.
  4. 4. A variable is assigned inside a for loop. Is it available after endfor?

    assign and capture are not block scoped, so the value stays available after the loop. Only the loop variable and forloop are limited to the loop.

Summary

  • assign stores a value or a filtered expression; it has no operators, so math uses filters.
  • Build class lists and arrays by re-assigning a variable through append or concat; there is no push and no array literal.
  • capture stores rendered output as a string and keeps whitespace unless you trim with -.
  • increment and decrement are counters that print as they change and are independent from assign variables.
  • assign and capture are not block scoped; loop variables are. Do not reuse global object names, and use default for fallbacks.

Next: Filters: Strings, Math, Arrays