Skip to contentSkip to navigationSkip to topbar
Rate this page:
On this page

Liquid Template Language


Liquid is a template language used to create dynamic content. There are two types of markup in Liquid: Output and Tag.

  • Output markup (which may resolve to text) is surrounded by

_10
{{ matched pairs of curly brackets (ie, braces) }}

  • Tag markup (which cannot resolve to text) is surrounded by

_10
{% matched pairs of curly brackets and percent signs %}


Output

output page anchor

An output statement is a set of double curly braces containing an expression; when the template is rendered, it gets replaced with the value of that expression.

Here is a simple example of output:


_10
Hello {{name}}
_10
Hello {{user.name}}
_10
Hello {{ 'tobi' }}

Expressions and Variables

expressions-and-variables page anchor

Expressions are statements that have values. Liquid templates can use expressions in several places; most often in output statements, but also as arguments to some tags or filters.

Liquid accepts the following kinds of expressions:

  • Variables. The most basic kind of expression is just the name of a variable. Liquid variables are named like Ruby variables: they should consist of alphanumeric characters and underscores, should always start with a letter, and do not have any kind of leading sigil (that is, they look like var_name , not $var_name ).
  • Array or hash access. If you have an expression (usually a variable) whose value is an array or hash, you can use a single value from that array/hash as follows:
    • my_variable[<KEY EXPRESSION>] — The name of the variable, followed immediately by square brackets containing a key expression.
      • For arrays, the key must be a literal integer or an expression that resolves to an integer.
      • For hashes, the key must be a literal quoted string or an expression that resolves to a string.
    • my_hash.key — Hashes also allow a shorter "dot" notation, where the name of the variable is followed by a period and the name of a key. This only works with keys that don't contain spaces, and (unlike the square bracket notation) does not allow the use of a key name stored in a variable.
    • Note: if the value of an access expression is also an array or hash, you can access values from it in the same way, and can even combine the two methods. (For example, site.posts[34].title .)
  • Array first and last. If you have an expression whose value is an array, you can follow it with .first or .last to resolve to its first or last element.
  • Array or hash size. If you have an expression whose value is an array or hash, you can follow it with .size to resolve to the number of elements in the original expression, as an integer.
  • Strings. Literal strings must be surrounded by double quotes or single quotes ( "my string" or 'my string' ). There is no difference; neither style allows variable interpolation.
  • Integers. Integers must not be quoted.
  • Booleans and nil. The literal values true , false , and nil .

Note that there is no way to write a literal array or hash as an expression; arrays and hashes must be passed into the template, or constructed obliquely with a tag or output statement.

Advanced output: Filters

advanced-output-filters page anchor

Output markup can take filters, which modify the result of the output statement. You can invoke filters by following the output statement's main expression with:

  • A pipe character ( | )
  • The name of the filter
  • Optionally, a colon ( : ) and a comma-separated list of additional parameters to the filter. Each additional parameter must be a valid expression, and each filter pre-defines the parameters it accepts and the order in which they must be passed.

Filters can also be chained together by adding additional filter statements (starting with another pipe character). The output of the previous filter will be the input for the next one.


_10
Hello {{ 'tobi' | upcase }}
_10
Hello tobi has {{ 'tobi' | size }} letters!
_10
Hello {{ '*tobi*'| upcase }}
_10
Hello {{ 'now' | date: "%Y %h" }}

Under the hood, a filter is a method that takes one or more parameters and returns a value. Parameters are passed to filters by position: the first parameter is the expression preceding the pipe character, and additional parameters can be passed using the name: arg1, arg2 syntax described above.

  • append - append a string, e.g. {{ 'foo' | append:'bar' }} #=> 'foobar'
  • capitalize - capitalize words in the input sentence
  • ceil - rounds a number up to the nearest integer, e.g. {{ 4.6 | ceil }} #=> 5
  • date - reformat a date ( syntax reference )
  • default - returns the given variable unless it is null or the empty string, when it will return the given value, e.g. {{ undefined_variable | default: "Default value" }} #=> "Default value"
  • divided_by - integer division, e.g. For integer output {{ 10 | divided_by:3 }} #=> 3 For float output {{ 10 | divided_by:3.0 }} #=> 3.333333333335 . It is advisable to use round function when using float.
  • downcase - convert an input string to lowercase
  • escape_once - returns an escaped version of html without affecting existing escaped entities
  • escape - html escape a string
  • first - get the first element of the passed in array
  • floor - rounds a number down to the nearest integer, e.g. {{ 4.6 | floor }} #=> 4
  • join - join elements of the array with certain character between them
  • last - get the last element of the passed in array
  • lstrip - strips all whitespace from the beginning of a string
  • map - map/collect an array on a given property
  • minus - subtraction, e.g. {{ 4 | minus:2 }} #=> 2
  • modulo - remainder, e.g. {{ 3 | modulo:2 }} #=> 1
  • newline_to_br - replace each newline (\n) with html break
  • plus - addition, e.g. {{ '1' | plus:'1' }} #=> 2 , {{ 1 | plus:1 }} #=> 2
  • prepend - prepend a string, e.g. {{ 'bar' | prepend:'foo' }} #=> 'foobar'
  • remove_first - remove the first occurrence, e.g. {{ 'barbar' | remove_first:'bar' }} #=> 'bar'
  • remove - remove each occurrence, e.g. {{ 'foobarfoobar' | remove:'foo' }} #=> 'barbar'
  • replace_first - replace the first occurrence e.g. {{ 'barbar' | replace_first:'bar','foo' }} #=> 'foobar'
  • replace - replace each occurrence, e.g. {{ 'foofoo' | replace:'foo','bar' }} #=> 'barbar'
  • reverse - reverses the passed in array. To reverse text, convert to an array first: {{ 'foobar' | split: "" | reverse | join: ""}} => 'raboof'
  • round - rounds input to the nearest integer or specified number of decimals, e.g. {{ 4.5612 | round: 2 }} #=> 4.56
  • rstrip - strips all whitespace from the end of a string
  • size - return the size of an array or string
  • slice - slice a string. Takes an offset and length, e.g. {{ "hello" | slice: -3, 3 }} #=> llo
  • sort - sort elements of the array
  • split - split a string on a matching pattern, e.g. {{ "a~b" | split:"~" }} #=> ['a','b']
  • strip_html - strip html from string
  • strip_newlines - strip all newlines (\n) from string
  • strip - strips all whitespace from both ends of the string
  • times - multiplication, e.g {{ 5 | times:4 }} #=> 20
  • to_json - convert Liquid objects to valid JSON, e.g. {{ flow.data | to_json }} #=> {"foo":"bar","baz":"bat"}
  • truncate - truncate a string down to x characters. It also accepts a second parameter that will append to the string (defaults to "..."), e.g. {{ 'foobarfoobar' | truncate: 5, '.' }} #=> 'foob.'
  • truncatewords - truncate a string down to x words. It also accepts a second parameter that will append to the string (defaults to "..."), e.g. {{ 'foo bar' | truncatewords: 1, '...' }} #=> 'foo...'
  • uniq - removed duplicate elements from an array, optionally using a given property to test for uniqueness
  • upcase - convert an input string to uppercase
  • url_encode - url encode a string
  • url_decode - decodes a string that has been encoded as a URL or by url_encode

Tags are used for the logic in your template. Here is a list of currently supported tags:

  • assign - Assigns some value to a variable
  • capture - Block tag that captures text into a variable
  • case - Block tag, its the standard case...when block
  • comment - Block tag, comments out the text in the block
  • cycle - Cycle is usually used within a loop to alternate between values, like colors or DOM classes.
  • for - For loop
  • break - Exits a for loop
  • continue Skips the remaining code in the current for loop and continues with the next loop
  • if - Standard if/else block
  • include - Includes another template; useful for partials
  • raw - temporarily disable tag processing to avoid syntax conflicts.
  • unless - Mirror of if statement

Any content that you put between {% comment %} and {% endcomment %} tags is turned into a comment.


_10
We made 1 million dollars {% comment %} in losses {% endcomment %} this year

Raw temporarily disables tag processing. This is useful for generating content (eg, Mustache, Handlebars) which uses conflicting syntax.


_10
{% raw %}
_10
In Handlebars, {{ this }} will be HTML-escaped, but {{{ that }}} will not.
_10
{% endraw %}

if / else statements should be familiar from other programming languages. Liquid implements them with the following tags:

  • {% if <CONDITION> %} ... {% endif %} — Encloses a section of template which will only be run if the condition is true.
  • {% elsif <CONDITION> %} — Can optionally be used within an if ... endif block. Specifies another condition; if the initial "if" fails, Liquid tries the "elsif", and runs the following section of template if it succeeds. You can use any number of elsifs in an if block.
  • {% else %} — Can optionally be used within an if ... endif block, after any "elsif" tags. If all preceding conditions fail, Liquid will run the section of template following the "else" tag.
  • {% unless <CONDITION> %} ... {% endunless %} — The reverse of an "if" statement. Don't use "elsif" or "else" with an unless statement.

The condition of an if, elsif or unless tag should be either a normal Liquid expression or a comparison using Liquid expressions. Note that the comparison operators are implemented by the "if"-like tags; they don't work anywhere else in Liquid.

The available comparison operators are:

  • ==, !=, and <> — equality and inequality (the latter two are synonyms)
    • There's a secret special value empty (unquoted) that you can compare arrays to; the comparison is true if the array has no members.
  • <, <=, >, >= — less/greater-than
  • contains — a wrapper around Ruby's include? method, which is implemented on strings, arrays, and hashes. If the left argument is a string and the right isn't, it stringifies the right.

The available Boolean operators are:

  • and
  • or

Note that there is NO "not" operator. Also note that you CANNOT use parentheses to control order of operations, and the precedence of the operators appears to be unspecified. So when in doubt, use nested "if" statements instead of risking it.

Liquid expressions are tested for "truthiness" in what looks like a Ruby-like way:

  • true is true.
  • false is false.
  • Any string is true, including the empty string.
  • Any array is true.
  • Any hash is true.
  • Any nonexistent/nil value (like a missing member of a hash) is false. 000

_10
{% if user %}
_10
Hello {{ user.name }}
_10
{% endif %}


_10
# Same as above
_10
{% if user != null %}
_10
Hello {{ user.name }}
_10
{% endif %}


_10
{% if user.name == 'tobi' %}
_10
Hello tobi
_10
{% elsif user.name == 'bob' %}
_10
Hello bob
_10
{% endif %}


_10
{% if user.name == 'tobi' or user.name == 'bob' %}
_10
Hello tobi or bob
_10
{% endif %}


_10
{% if user.name == 'bob' and user.age > 45 %}
_10
Hello old bob
_10
{% endif %}


_10
{% if user.name != 'tobi' %}
_10
Hello non-tobi
_10
{% endif %}


_10
# Same as above
_10
{% unless user.name == 'tobi' %}
_10
Hello non-tobi
_10
{% endunless %}


_10
# Check for the size of an array
_10
{% if user.payments == empty %}
_10
you never paid !
_10
{% endif %}
_10
_10
{% if user.payments.size > 0 %}
_10
you paid !
_10
{% endif %}


_10
{% if user.age > 18 %}
_10
Login here
_10
{% else %}
_10
Sorry, you are too young
_10
{% endif %}


_10
# array = 1,2,3
_10
{% if array contains 2 %}
_10
array includes 2
_10
{% endif %}


_10
# string = 'hello world'
_10
{% if string contains 'hello' %}
_10
string includes 'hello'
_10
{% endif %}

If you need more conditions, you can use the case statement:


_10
{% case condition %}
_10
{% when 1 %}
_10
hit 1
_10
{% when 2 or 3 %}
_10
hit 2 or 3
_10
{% else %}
_10
... else ...
_10
{% endcase %}

Example:


_10
{% case template %}
_10
_10
{% when 'label' %}
_10
// {{ label.title }}
_10
{% when 'product' %}
_10
// {{ product.vendor }} / {{ product.title }}
_10
{% else %}
_10
// {{page_title}}
_10
{% endcase %}

Often you have to alternate between different colors or similar tasks. Liquid has built-in support for such operations, using the cycle tag.


_10
{% cycle 'one', 'two', 'three' %}
_10
{% cycle 'one', 'two', 'three' %}
_10
{% cycle 'one', 'two', 'three' %}
_10
{% cycle 'one', 'two', 'three' %}

will result in


_10
one
_10
two
_10
three
_10
one

If no name is supplied for the cycle group, then it's assumed that multiple calls with the same parameters are one group.

If you want to have total control over cycle groups, you can optionally specify the name of the group. This can even be a variable.


_10
{% cycle 'group 1': 'one', 'two', 'three' %}
_10
{% cycle 'group 1': 'one', 'two', 'three' %}
_10
{% cycle 'group 2': 'one', 'two', 'three' %}
_10
{% cycle 'group 2': 'one', 'two', 'three' %}

will result in


_10
one
_10
two
_10
one
_10
two

Liquid allows for loops over collections:


_10
{% for item in array %}
_10
{{ item }}
_10
{% endfor %}

Allowed collection types

allowed-collection-types page anchor

For loops can iterate over arrays, hashes, and ranges of integers.

When iterating a hash, item[0] contains the key, and item[1] contains the value:


_10
{% for item in hash %}
_10
{{ item[0] }}: {{ item[1] }}
_10
{% endfor %}

Instead of looping over an existing collection, you can also loop through a range of numbers. Ranges look like (1..10) — parentheses containing a start value, two periods, and an end value. The start and end values must be integers or expressions that resolve to integers.


_10
# if item.quantity is 4...
_10
{% for i in (1..item.quantity) %}
_10
{{ i }}
_10
{% endfor %}
_10
# results in 1,2,3,4

You can exit a loop early with the following tags:

  • {% continue %} — immediately end the current iteration, and continue the "for" loop with the next value.
  • {% break %} — immediately end the current iteration, then completely end the "for" loop.

Both of these are only useful when combined with something like an "if" statement.


_10
{% for page in pages %}
_10
# Skip anything in the hidden_pages array, but keep looping over the rest of the values
_10
{% if hidden_pages contains page.url %}
_10
{% continue %}
_10
{% endif %}
_10
# If it's not hidden, print it.
_10
* [page.title](page.url)
_10
{% endfor %}


_10
{% for page in pages %}
_10
* [page.title](page.url)
_10
# After we reach the "cutoff" page, stop the list and get on with whatever's after the "for" loop:
_10
{% if cutoff_page == page.url %}
_10
{% break %}
_10
{% endif %}
_10
{% endfor %}

During every for loop, the following helper variables are available for extra styling needs:


_10
forloop.length # => length of the entire for loop
_10
forloop.index # => index of the current iteration
_10
forloop.index0 # => index of the current iteration (zero based)
_10
forloop.rindex # => how many items are still left?
_10
forloop.rindex0 # => how many items are still left? (zero based)
_10
forloop.first # => is this the first iteration?
_10
forloop.last # => is this the last iteration?

There are several optional arguments to the for tag that can influence which items you receive in your loop and what order they appear in:

  • limit:<INTEGER> lets you restrict how many items you get.
  • offset:<INTEGER> lets you start the collection with the nth item.
  • reversed iterates over the collection from last to first.

Restricting elements:


_10
# array = [1,2,3,4,5,6]
_10
{% for item in array limit:2 offset:2 %}
_10
{{ item }}
_10
{% endfor %}
_10
# results in 3,4

Reversing the loop:


_10
{% for item in collection reversed %} {{item}} {% endfor %}

A for loop can take an optional else clause to display a block of text when there are no items in the collection:


_10
# items => []
_10
{% for item in items %}
_10
{{ item.title }}
_10
{% else %}
_10
There are no items!
_10
{% endfor %}

You can store data in your own variables, to be used in output or other tags as desired. The simplest way to create a variable is with the assign tag, which has a pretty straightforward syntax:


_10
{% assign name = 'freestyle' %}
_10
_10
{% for t in collections.tags %}{% if t == name %}
_10
<p>Freestyle!</p>
_10
{% endif %}{% endfor %}

(information)

Info

Variables that are created using the assign tag only exist within the widget where they are created.

To create or modify variables that are accessible throughout your flow via other widgets under the key {{flow.variables.<key>}}, use the Set Variables widget instead.

Another way of doing this would be to assign true / false values to the variable:


_10
{% assign freestyle = false %}
_10
_10
{% for t in collections.tags %}{% if t == 'freestyle' %}
_10
{% assign freestyle = true %}
_10
{% endif %}{% endfor %}
_10
_10
{% if freestyle %}
_10
<p>Freestyle!</p>
_10
{% endif %}

If you want to combine a number of strings into a single string and save it to a variable, you can do that with the capture tag. This tag is a block which "captures" whatever is rendered inside it, then assigns the captured value to the given variable instead of rendering it to the screen.


_10
{% capture attribute_name %}{{ item.title | handleize }}-{{ i }}-color{% endcapture %}
_10
_10
<label for="{{ attribute_name }}">Color:</label>
_10
<select name="attributes[{{ attribute_name }}]" id="{{ attribute_name }}">
_10
<option value="red">Red</option>
_10
<option value="green">Green</option>
_10
<option value="blue">Blue</option>
_10
</select>

Dates can be formatted with a variety of options.

The input to the date filter must be one the following, specific values in order to avoid errors:

  • The string 'now' , which will be interpreted as the current time
  • The intended time, in seconds , as a number
  • The intended time, formatted as a string in one of the two following formats:
    • yyyy-MM-dd HH:mm:ss
    • EEE MMM dd hh:mm:ss yyyy

For example, any of these inputs are valid:


_11
# Format the current time using the 'now' keyword
_11
Hello {{ 'now' | date: "%Y %d" }}
_11
_11
# Format a given time, input as the number of seconds
_11
Hello {{ 1623959503 | date: "%Y %d" }}
_11
_11
# Format a given time, input as a string in "yyyy-MM-dd HH:mm:ss" format
_11
Hello {{ '2021-06-17 12:51:43' | date: "%Y %d" }}
_11
_11
# Format a given time, input as a string in "EEE MMM dd hh:mm:ss yyyy" format
_11
Hello {{ 'Thu Jun 17 12:51:43 2021' | date: "%Y %d" }}

(warning)

Warning

When using the now keyword instead of a specific date, the resulting time will be output in US Pacific Time, not UTC.

The following format tokens are accepted for formatting your date:


_29
%a - The abbreviated weekday name ("Sun")
_29
%A - The full weekday name ("Sunday")
_29
%b - The abbreviated month name ("Jan")
_29
%B - The full month name ("January")
_29
%c - The preferred local date and time representation
_29
%d - Day of the month (01..31)
_29
%e - Day of the month (1..31)
_29
%H - Hour of the day, 24-hour clock (00..23)
_29
%I - Hour of the day, 12-hour clock (01..12)
_29
%j - Day of the year (001..366)
_29
%k - Hour of the day, 24-hour clock (0..23)
_29
%l - Hour of the day, 12-hour clock (0..12)
_29
%m - Month of the year (01..12)
_29
%M - Minute of the hour (00..59)
_29
%p - Meridian indicator ("AM" or "PM")
_29
%S - Second of the minute (00..60)
_29
%U - Week number of the current year,
_29
starting with the first Sunday as the first
_29
day of the first week (00..53)
_29
%W - Week number of the current year,
_29
starting with the first Monday as the first
_29
day of the first week (00..53)
_29
%w - Day of the week (Sunday is 0, 0..6)
_29
%x - Preferred representation for the date alone, no time
_29
%X - Preferred representation for the time alone, no date
_29
%y - Year without a century (00..99)
_29
%Y - Year with century
_29
%Z - Time zone name
_29
%% - Literal "%" character


In Liquid, you can include a hyphen in your tag syntax {{-, -}}, {%-, and -%} to strip whitespace from the left or right side of a rendered tag.

If you don't want any of your tags to print whitespace, as a general rule you can add hyphens to both sides of all your tags ({%- and -%}).

The following example ensures whitespace doesn't get concatenated to the integer as it increments:


_10
{%- if flow.variables.count -%}
_10
{{flow.variables.count | plus: 1}}
_10
{%- else -%}
_10
0
_10
{%- endif -%}


A rendered string has a maximum length of 16,384 characters.


In a Studio Flow, a liquid variable containing a value greater than 16,384 characters means that the value is not rendered in the output. The liquid variable, {{some_var}} for example, is rendered in the output instead.


Rate this page: