Types

 

Liquid objects can have one of five types:

 

  • String
  • Number
  • Boolean
  • Nil
  • Array
TitleCodeDescription
StringDeclare a string by wrapping a variable’s value in single or double quotes

Comment

Code:

Anything you put between {% comment %} and {% endcomment %} tags is turned into a comment.

 

output:

Anything you put between tags is turned into a comment.


Control flow statements


TitleDescriptionCodeOutput
IfExecutes a block of code only if a certain condition is true.{% if product.title == “Awesome Shoes” %} These shoes are awesome! {% endif %}These shoes are awesome!
unlessExecutes a block of code only if a certain condition is true.{% unless product.title == “Awesome Shoes” %}These shoes are not awesome.{% endunless %}These shoes are not awesome.
elsif / elseAdds more conditions within an if or unless block.{% if customer.name == “kevin” %} Hey Kevin!{% elsif customer.name == “anonymous” %} Hey Anonymous!{% else %} Hi Stranger!{% endif %}Hey Anonymous!
case/whenCreates a switch statement to compare a variable with different values. case initializes the switch statement, and when compares its values.{% assign handle = “cake” %}{% case handle %} {% when “cake” %} This is a cake {% when “cookie” %} This is a cookie {% else %} This is not a cake nor a cookie{% endcase %}This is a cake

Iteration statements


 

TitleDescriptionCodeOutput
For loopRepeatedly executes a block of code.{% for product in collection.products %} {{ product.title }} {% endfor %}hat shirt pants
BreakCauses the loop to stop iterating when it encounters the break tag.{% for i in (1..5) %} {% if i == 4 %} {% break %} {% else %} {{ i }} {% endif %}{% endfor %}1 2 3
ContinueCauses the loop to skip the current iteration when it encounters the continue tag.{% for i in (1..5) %} {% if i == 4 %} {% continue %} {% else %} {{ i }} {% endif %}{% endfor %}1 2 3 5
LimitLimits the loop to the specified number of iterations.{% for item in array limit:2 %} {{ item }}{% endfor %}1 2
OffsetBegins the loop at the specified index.{% for item in array offset:2 %} {{ item }}{% endfor %}3 4 5 6
RangeDefines a range of numbers to loop through. The range can be defined by both literal and variable numbers.{% for i in (3..5) %} {{ i }}{% endfor %}{% assign num = 4 %}{% for i in (1..num) %} {{ i }}{% endfor %}3 4 5
1 2 3 4
ReversedReverses the order of the loop. Note that this flag’s spelling is different from the filter reverse.{% for item in array reversed %} {{ item }}{% endfor %}6 5 4 3 2 1
CycleLoops through a group of strings and prints them in the order that they were passed as arguments. Each time cycle is called, the next string argument is printed.{% cycle “one”, “two”, “three” %}{% cycle “one”, “two”, “three” %}{% cycle “one”,“two”,“three” %}{% cycle “one”, “two”, “three” %}one two three one
Cycle (parameters)cycle accepts a “cycle group” parameter in cases where you need multiple cycle blocks in one template. If no name is supplied for the cycle group, then it is assumed that multiple calls with the same parameters are one group.{% cycle “first”: “one”, “two”, “three” %}{% cycle “second”: “one”, “two”, “three” %}{% cycle “second”: “one”, “two”, “three” %}{% cycle “first”: “one”, “two”, “three” %}one one two two
TablerowGenerates an HTML table. Must be wrapped in opening <table> and closing </table> HTML tags.<table>{% tablerow product in collection.products %} {{ product.title }}{% endtablerow %}</table><table> <tr class=”row1″> <td class=”col1″> Cool Shirt </td> <td class=”col2″>
Alien Poster </td> <td class=”col3″> Batman Poster </td> <td class=”col4″> Bullseye
Shirt </td> <td class=”col5″> Another Classic Vinyl </td> <td class=”col6″> Awesome
Jeans </td> </tr></table>
Tablerow (parameters)cols: Defines how many columns the tables should have.{% tablerow product in collection.products cols:2 %} {{ product.title }}{% endtablerow %}<table> <tr class=”row1″> <td class=”col1″> Cool Shirt </td> <td class=”col2″>
Alien Poster </td> </tr> <tr class=”row2″> <td class=”col1″> Batman Poster </td>
<td class=”col2″> Bullseye Shirt </td> </tr> <tr class=”row3″> <td class=”col1″>
Another Classic Vinyl </td> <td class=”col2″> Awesome Jeans </td> </tr></table>

Raw

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


Variable

To create a variable use the following methods:

 

TitleDescriptionCodeOutput
assignCreates a new variable.{% assign my_variable = 1 %} {{my_variable}}1
captureCaptures the string inside of the opening and closing tags and assigns it to a variable. Variables created
through capture are strings.
{% capture my_variable %}I am being captured.{% endcapture %}{{ my_variable }}I am being captured.
incrementCreates a new number variable, and increases its value by one every time it is called. The initial value is 0.{% increment my_counter %}{% increment my_counter %}{% increment my_counter %}0 1 2
decrementCreates a new number variable, and decreases its value by one every time it is called. The initial value is -1.{% decrement my_counter %}{% decrement my_counter %}{% decrement my_counter %}-1 -2 -3

Filters


 

TitleDescriptionCodeOutput
absReturns the absolute value of a number.{{ -17 | abs }}17
appendConcatenates two strings and returns the concatenated value.{{ “/my/fancy/url” | append: “.html” }}/my/fancy/url.html
at_leastLimits a number to a minimum value.{{ 4 | at_least: 5 }}5
at_mostLimits a number to a maximum value.{{ 4 | at_most: 5 }}4
capitalizeMakes the first character of a string capitalized.{{ “title” | capitalize }}Title
ceilRounds the input up to the nearest whole number. Liquid tries to convert the input to a number before the filter is applied.{{ 1.2 | ceil }}2
compactRemoves any nil values from an array. In this example site.pages is an array in config.yml page which contains the categories of the page. If any page which do not contain the category will be isplayed as an empty value in this array. By using compact the nil value of this array is removed.{% assign site_categories = site.pages | map: “category” | compact %}{% for category in site_categories %}-{{ category }}{% endfor %}– business
– celebrities
– lifestyle
– sports
– technology
concatConcatenates (joins together) multiple arrays. The resulting array contains all the items from the input arrays.{% assign fruits = “apples, oranges, peaches” | split: “, “ %}{% assign vegetables = “carrots, turnips, potatoes” | split: “, “ %}{% assign everything = fruits | concat: vegetables %}{% for item in everything %}-{{ item }}{% endfor %}– apples
– oranges
– peaches
– carrots
– turnips
– potatoes
dateConverts a timestamp into another date format.{{ article.published_at | date: “%a, %b %d, %y” }}Fri, Jul 20, 15
defaultAllows you to specify a fallback in case a value doesn’t exist. default will show its value if the left side is nil, false, or empty. In this example, product_price is not defined, so the default value is used.{{ product_price | default: 2.99 }}2.99
divided_byDivides a number by another number.{{ 16 | divided_by: 4 }}4
downcaseMakes each character in a string lowercase. It has no effect on strings which are already all lowercase.{{ “Parker Moore” | downcase }}parker moore
escapeEscapes a string by replacing characters with escape sequences (so that the string can be used in a URL, for example). It doesn’t change strings that don’t have anything to escape.{{ “Have you read ‘James & the Giant Peach’?” | escape }}Have you read 'James &amp; the Giant Peach'?
escape_onceEscapes a string without changing existing escaped entities. It doesn’t change strings that don’t have anything to escape.{{ “1 < 2 & 3” | escape_once }}1 &lt; 2 &amp; 3
firstReturns the first item of an array.{{ “Ground control to Major Tom.” | split: “ “ | first }}Ground
floorRounds the input down to the nearest whole number. Liquid tries to convert the input to a number before the filter is applied.{{ 1.2 | floor }}1
joinCombines the items in an array into a single string using the argument as a separator.{% assign beatles = “John, Paul, George, Ringo” | split: “, “ %}{{ beatles | join: “ and “ }}John and Paul and George and Ringo
lastReturns the last item of an array.{{ “Ground control to Major Tom.” | split: “ “ | last }}Tom.
lstripRemoves all whitespace (tabs, spaces, and newlines) from the left side of a string. It does not affect spaces between words.{{ “ So much room for activities! “ | lstrip }}So much room for activities!
mapCreates an array of values by extracting the values of a named property from another object.{% assign site_categories = site.pages | map: “category” | compact %}{% for category in site_categories %}-{{ category }}{% endfor %}– business
– celebrities
– lifestyle
– sports
– technology
minusSubtracts a number from another number.{{ 4 | minus: 2 }}2
moduloReturns the remainder of a division operation{{ 3 | modulo: 2 }}1
newline_to_brReplaces every newline in a string with an HTML line break.{% capture string_with_newlines %}Hello there{% endcapture %}{{ string_with_newlines | newline_to_br }}Hello
there
plusAdds a number to another number.{{ 4 | plus: 2 }}6
prependAdds the specified string to the beginning of another string.{{ “apples, oranges, and bananas” | prepend: “Some fruit: “ }}Some fruit: apples, oranges, and bananas
removeRemoves every occurrence of the specified substring from a string.{{ “I strained to see the train through the rain” | remove: “rain” }}I sted to see the t through the
remove_firstRemoves only the first occurrence of the specified substring from a string.{{ “I strained to see the train through the rain” | remove_first: “rain” }}I sted to see the train through the rain
replaceReplaces every occurrence of the first argument in a string with the second argument.{{ “Take my protein pills and put my helmet on” | replace: “my”, “your” }}Take your protein pills and put your helmet on
replace_firstReplaces only the first occurrence of the first argument in a string with the second argument.{{ “Take my protein pills and put my helmet on” | replace_first: “my”, “your” }}Take your protein pills and put my helmet on
reverseReverses the order of the items in an array. reverse cannot reverse a string.{% assign my_array = “apples, oranges, peaches, plums” | split: “, “ %}{{ my_array | reverse | join: “, “ }}plums, peaches, oranges, apples
roundRounds a number to the nearest integer or, if a number is passed as an argument, to that number of decimal places.{{ 1.2 | round }}1
rstripRemoves all whitespace (tabs, spaces, and newlines) from the right side of a string. It does not affect spaces between words{{ “ So much room for activities! “ | rstrip }}So much room for activities!
sizeReturns the number of characters in a string or the number of items in an array.{{ “Ground control to Major Tom.” | size }}28
sliceReturns a substring of 1 character beginning at the index specified by the first argument. An optional second argument specifies the length of the substring to be returned.String indices are numbered starting from 0.{{ “Liquid” | slice: 0 }}L
sortSorts items in an array in case-sensitive order.{% assign my_array = “zebra, octopus, giraffe, Sally Snake” | split: “, “ %}{{ my_array | sort | join: “, “}}Sally Snake, giraffe, octopus, zebra
sort_naturalSorts items in an array in case-insensitive order.{% assign my_array = “zebra, octopus, giraffe, Sally Snake” | split: “, “ %}{{ my_array | sort_natural | join: “, “ }}giraffe, octopus, Sally Snake, zebra
splitDivides a string into an array using the argument as a separator. split is commonly used to convert comma-separated items from a string to an array.{% assign beatles = “John, Paul, George, Ringo” | split: “, “ %}{% for member in beatles %} {{ member }}{% endfor %}John Paul George Ringo
stripRemoves all whitespace (tabs, spaces, and newlines) from both the left and right sides of a string. It does not affect spaces between words.{{ “ So much room for activities! “ | strip }}So much room for activities!
strip_htmlRemoves any HTML tags from a string.{{ “Have you read Ulysses ?” | strip_html }}Have you read Ulysses?
strip_newlinesRemoves any newline characters (line breaks) from a string.{% capture string_with_newlines %}Hello there{% endcapture %}{{ string_with_newlines | strip_newlines }}Hellothere
timesMultiplies a number by another number.{{ 3 | times: 2 }}6
truncateShortens a string down to the number of characters passed as an argument. If the specified number of characters is less than the length of the string, an ellipsis (…) is appended to the string and is included in the character count.{{ “Ground control to Major Tom.” | truncate: 20 }Ground control to…
truncatewordsShortens a string down to the number of words passed as an argument. If the specified number of words is less than the number of words in the string, an ellipsis (…) is appended to the string.{{ “Ground control to Major Tom.” | truncatewords: 3 }}Ground control to…
uniqRemoves any duplicate elements in an array.{% assign my_array = “ants, bugs, bees, bugs, ants” | split: “, “ %}{{ my_array | uniq | join: “, “ }}ants, bugs, bees
upcaseMakes each character in a string uppercase. It has no effect on strings which are already all uppercase.{{ “Parker Moore” | upcase }}PARKER MOORE
url_decodeDecodes a string that has been encoded as a URL or by url_encode.{{ “%27Stop%21%27+said+Fred” | url_decode }}‘Stop!’ said Fred
url_encodeConverts any URL-unsafe characters in a string into percent-encoded characters.{{ “[email protected]” | url_encode }}john%40liquid.com
whereCreates an array including only the objects with a given property value, or any truthy value by default.In this example, assume you have a list of products and you want to show your kitchen products separately. Using where, you can create an array containing only the products that have a “type” of “kitchen”.All products:{% for product in products %}- {{ product.title }}{% endfor %}{% assign kitchen_products = products where: “type”, “kitchen” %}Kitchen products:{% for product in kitchen_products %}- {{ product.title }}{% endfor %}All products:
– Vacuum
– Spatula
– Television
– Garlic press
Kitchen products:
– Spatula
– Garlic press