Liquid is an open-source template language created by Shopify that written in Ruby. Jekyll uses it to process templates and pages for your static pages. With this powerful tool, you can get complex tasks done without additional plugins.
Only a subset of Liquid features are implemented by Jekyll.2 This means that some of the tags and filters listed on https://shopify.github.io/liquid/ may not work in Jekyll. Often the Jekyll project will wait for a stable release of Liquid rather than using a beta or release candidate version. To see which version of Liquid Jekyll is using, check the runtime dependencies section of Jekyll’s gem page.
Here, I’m going to demonstrate examples from documents of Shopify, how it works and test its ability with Jekyll. As this post was generated by Jekyll (4.0.1) (this post was update on 2020.05.20), the following examples should work as presented when you put them into practices.
Liquid basics
Liquid code can be categorized into objects, tags, and filters.
Objects
Objects tell Liquid where to show content on a page and denoted by double curly braces: {{ and }}.
Input:
{{page.title}}
Output:
Using Liquid in Jekyll - Live with Demos
Tags
Tags create the logic and control flow for templates. They are denoted by curly braces and percent signs: {% and %}.
The markup used in tags does not produce any visible text. This means that you can assign variables and create conditions and loops without showing any of the Liquid logic on the output page.
Input:
{%ifstatement%}
Hey there, you are visiting {{page.url|prepend:site.url}}.
{%endif%}
Output:
Hey there, you are visiting https://frankindev.com/2016/08/20/using-liquid-in-jekyll/.
Moreover, multiple filters can be used on one output, they are applied (chained) from left to right.
Input:
{{page.title|upcase|prepend:"You're visiting: "}}
Output:
You're visiting: USING LIQUID IN JEKYLL - LIVE WITH DEMOS
Examples of filters available will present in the following section.
Operators
Basic operators
==
equals
!=
does not equal
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
or
logical or
and
logical and
For example:
{%ifproduct.title=="Awesome Shoes"%}
These shoes are awesome!
{%endif%}
You can use multiple operators in a single tag:
{%ifproduct.type=="Shirt"orproduct.type=="Shoes"%}
This is a shirt or a pair of shoes.
{%endif%}
Contains
contains checks for the presence of a substring inside a string:
{%ifpage.titlecontains'Pack'%}
This page's title contains the word Pack.
{%endif%}
contains can also check for the presence of a string in an array of strings:
{%ifpage.tagscontains'Hello'%}
This page has been tagged with 'Hello'.
{%endif%}
contains can only search strings. You cannot use it to check for an object in an array of objects.
Order of operations
In tags with more than one and or or operator, operators are checked in order from right to left. You cannot change the order of operations using parentheses — parentheses are invalid characters in Liquid and will prevent your tags from working.
{%iftrueorfalseandfalse%}
This evaluates to true, since the `and` condition is checked first.
{%endif%}
{%iftrueandfalseandfalseortrue%}
This evaluates to false, since the tags are checked like this:
true and (false and (false or true))
true and (false and true)
true and false
false
{%endif%}
Truthy and falsy
Truthy
All values in Liquid are truthy except nil and false.
In the example below, the string “Tobi” is not a boolean, but it is truthy in a conditional:
{%assigntobi="Tobi"%}{%iftobi%}
This condition will always be true.
{%endif%}
The falsy values in Liquid are nil and false, just them…
Summary
The table below summarises what is truth of falsy in Liquid.
truthy
False
true
✅
false
✅
nil
✅
string
✅
empty string
✅
0
✅
integer
✅
float
✅
array
✅
empty array
✅
page
✅
EmptyDrop
✅
Object types
Liquid objects can have one of these types:
string
number
boolean
nil
array
You can initialize Liquid variables with the assign or capture tag.
String
Declare a string by wrapping a variable’s value in single or double quotes:
{%assignmy_string="Hello World! This is Frank."%}
Number
Numbers include floats and integers:
{%assignmy_int=25%}{%assignmy_float=39.756%}
Boolean
Booleans are either true or false. No quotations are necessary when declaring a boolean:
{%assignfoo=true%}{%assignbar=false%}
Nil
Nil is a special empty value that is returned when Liquid code has no results. It is not a string with the characters “nil”. Nil is treated as false in the conditions of if blocks and other Liquid tags that check the truthfulness of a statement.
In the following example, the page.author does not exist (i.e. {{ page.author }} returns nil), Liquid will not print anything (except an blank line owns to the Liquid code):
{%ifpage.author%}
post by {{page.author}}{%endif%}{%ifpage.title%}
the title of this post: {{page.title}}{%endif%}
Output:
the title of this post: Using Liquid in Jekyll - Live with Demos
Array
Arrays hold lists of variables of any type. You cannot initialize arrays using only Liquid. You can, however, use the split filter to break a string into an array of substrings.
You can use square bracket [ ] notation to access a specific item in an array. Array indexing starts at zero.
Input:
{{page.tags[1]}}
Output:
liquid
Whitespace control
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. Normally, even if it doesn’t output text, any line of Liquid in your template will still output a blank line in the rendered HTML file:
Input:
{%assignmy_variable="tomato"%}{{my_variable}}
Output:
tomato
# notice the blank line before “tomato” in the rendered result
By including hyphens in your assign tag, you can strip the generated whitespace from the rendered template. But it seems not work when building with Jekyll 3.2.1 locally on my Windows PC. The recent Jekyll version now support this feature.
Input:
{%-assignmy_variable="tomato"-%}{{my_variable}}
Output:tomato
# notice the rendered result is adjust to "Output:", all whitespace generated are removed
If you don’t want any of your tags to output whitespace, as a general rule you can add hyphens to both sides of all of your tags ({%-, and -%}).
Or, you can test put the hyphen mark on either side of your tags.
Input:
{%assignusername="John G. Chalmers-Smith"-%}{%-ifusernameandusername.size>10-%}
Wow, {{username}}, you have a long name!
{%-else-%}
Hello there!
{%-endif%}
Output:
Wow, John G. Chalmers-Smith, you have a long name!
Ads by Google
Liquid tags
Okay, now let’s start with the import topic on tags.
Comment
Allows you to leave un-rendered code inside a Liquid template. Any text within the opening and closing comment blocks will not be output, and any Liquid code within will NOT be executes.
Input:
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
Control flow tags can change the information Liquid shows using programming logic.
case / when
Creates a switch statement to compare a variable with different values. case initializes the switch statement, and when compares its values.
Input:
{%assignhandle='cake'%}{%casehandle%}{%when'cake'%}
This is a cake
{%when'cookie'%}
This is a cookie
{%else%}
This is not a cake nor a cookie
{%endcase%}
Output:
This is a cake
# whitespace was cleaned intentionally
if
Executes a block of code only if a certain condition is true.
Input:
{%ifpage.category=='Web Notes'%}
This post is in Web.
{%endif%}
Output:
unless
The opposite of if – executes a block of code only if a certain condition is not met. This would be the equivalent by using if ... !=:
Input:
{%unlesspage.category=='Awesome'%}
This post is not awesome.
{%endunless%}
Output:
This post is not awesome.
elsif / else
Adds more conditions within an if or unless block.
{%ifcustomer.name=='kevin'%}
Hey Kevin!
{%elsifcustomer.name=='anonymous'%}
Hey Anonymous!
{%else%}
Hi Stranger!
{%endif%}
Iteration
Iteration tags run blocks of code repeatedly.
for
Repeatedly executes a block of code. For a full list of attributes available within a for loop, click to see the full doc.
Loops through a group of strings and outputs them in the order that they were passed as parameters. Each time cycle is called, the next string that was passed as a parameter is output. cycle must be used within a for loop block.
Input:
{%cycle'one','two','three'%}{%cycle'one','two','three'%}{%cycle'one','two','three'%}{%cycle'one','two','three'%}
Output:
one
two
three
one
Uses for cycle include:
applying odd/even classes to rows in a table
applying a unique class to the last product thumbnail in a row
cycle (parameters)
cycle accepts a parameter called cycle group 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.
Input:
{%cycle"first":"one","two","three"%}{%cycle"second":"one","two","three"%}{%cycle"second":"one","two","three"%}{%cycle"first":"one","two","three"%}
Output:
one
one
two
two
tablerow
Generates an HTML table. Must be wrapped in opening <table> and closing </table> HTML tags.
cols: defines how many columns the tables should have.
limit: limits the tablerow after a specific index.
offset: starts the tablerow after a specific index.
range: defines a range of numbers to loop through. The range can be defined by both literal and variable numbers.
Raw
Raw temporarily disables tag processing. This is useful for generating content which uses conflicting syntax.
Input:
{%raw%}
In Handlebars, {{ this }} will be HTML-escaped, but
{{{ that }}} will not.
{%endraw%}
Output:
In Handlebars, {{ this }} will be HTML-escaped, but
{{{ that }}} will not.
All Input in the examples in this post are wrapped in raw tags.
Variable
assign
Creates a new variable. Wrap a variable in quotations " to save it as a string.
capture
Captures the string inside of the opening and closing tags and assigns it to a variable. Variables created through {% capture %} are strings.
Input:
{%capturemy_variable%}I am being captured.{%endcapture%}{{my_variable}}
Output:
I am being captured.
increment
Creates a new number variable, and increases its value by one every time it is called. The initial value is 0.
Creates a new number variable, and decreases its value by one every time it is called. The initial value is -1.
Similar to increment, variables declared inside decrement are independent from variables created through assign or capture.
Liquid filters
As introduced in the basic section, filters are very useful in Liquid templates.
String
append / prepend
append concatenates two strings and returns the concatenated value, and also can be used with variables.
prepend adds the specified string to the beginning of another string.
Input:
{%assignfilename="/index.html"%}{{site.url|append:filename}}{{"apples, oranges, and bananas"|prepend:"Some fruit: "}}
Output:
https://frankindev.com/index.html
Some fruit: apples, oranges, and bananas
capitalize
Makes the first character of a string capitalized, and only capitalizes the first character of the string, so later words are not affected:
Input:
{{"this is a great title"|capitalize}}
Output:
This is a great title
Makes each character in a string lowercase (or upcase). It has no effect on strings which are already all lowercase (or upcase).
Input:
{{"Frank Lin"|downcase}}{{"Frank Lin"|upcase}}
Output:
frank lin
FRANK LIN
escape / escape_once
escape works to escapes 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.
escape_once can be used to escapes a string without changing existing escaped entities.
Input:
{{"Have you read 'James & the Giant Peach'?"|escape}}{{"1 < 2 & 3"|escape_once}}
Output:
Have you read 'James & the Giant Peach'?
1 < 2 & 3
lstrip / rstrip
lstrip removes all whitespace (tabs, spaces, and newlines) from the beginning of a string. The filter does not affect spaces between words. rstrip removes all whitespace from the right side of a string.
Input:
{{" So much room for activities! "|lstrip}}{{" So much room for activities! "|rstrip}}
Output:
So much room for activities!
So much room for activities!
Use remove to remove every occurrence of the specified substring from a string.
remove_first only removes the first occurrence of the specified substring from a string.
Input:
{{"I strained to see the train through the rain"|remove:"rain"}}{{"I strained to see the train through the rain"|remove_first:"rain"}}
Output:
I sted to see the t through the
I sted to see the train through the rain
replace / replace_first
Use replace to replace every occurrence of an argument in a string with the second argument.
And replace_first only replaces the first occurrence of the first argument in a string with the second argument.
Input:
{{"Take my protein pills and put my helmet on"|replace:"my","your"}}{%assignmy_string="Take my protein pills and put my helmet on"%}{{my_string|replace_first:"my","your"}}
Output:
Take your protein pills and put your helmet on
Take your protein pills and put my helmet on
size
Returns the number of characters in a string or the number of items in an array. size can also be used with dot notation (for example, {{ my_string.size }}). This allows you to use size inside tags such as conditionals.
Input:
{{"Ground control to Major Tom."|size}}{%assignmy_array="apples, oranges, peaches, plums"|split:", "%}{{my_array|size}}{%ifsite.pages.size>10%}
This site has more than 10 pages!
{%endif%}
Output:
28
4
This site has more than 10 pages!
slice
Returns a substring of character beginning at the index specified by the argument passed in. An optional second argument specifies the length of the substring to be returned.
String indices are numbered starting from 0. If the first parameter is a negative number, the indices are counted from the end of the string:
Input:
{{"Liquid"|slice:0}}{{"Liquid"|slice:2}}{{"Liquid"|slice:2,5}}{{"Liquid"|slice:-3,2}}
Output:
L
q
quid
ui
slugify
Convert a string into a lowercase URL slug.
The slugify filter accepts an option:
none: no characters
raw: spaces
default: spaces and non-alphanumeric characters
pretty: spaces and non-alphanumeric characters except for ._~!$&'()+,;=@
Convert quotes into smart quotes with SmartyPants3.
Input:
{{'Use "Jekyll" --- the static generator...'|smartify}}
Output:
Use “Jekyll” — the static generator…
split
Divides an input 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.
Input:
{{"a~b"|split:"~"}}
Output:
ab
strip
Removes all whitespace (tabs, spaces, and newlines) from both the left and right side of a string. It does not affect spaces between words.
Input:
{{" So much room for activities! "|strip}}
Output:
So much room for activities!
strip_html
Removes any HTML tags from a string.
strip_newlines
Removes any newline characters (line breaks) from a string.
truncate / truncatewords
truncate shortens a string down to the number of characters passed as a parameter. If the number of characters specified is less than the length of the string, an ellipsis (…) is appended to the string and is included in the character count.
Input:
{{"Ground control to Major Tom."|truncate:20}}
Output:
Ground control to...
Custom ellipsis
truncate takes an optional second parameter that specifies the sequence of characters to be appended to the truncated string. By default this is an ellipsis (…), but you can specify a different sequence. The length of the second parameter counts against the number of characters specified by the first parameter.
Input:
{{"Ground control to Major Tom."|truncate:25,", and so on"}}
Output:
Ground control, and so on
truncatewords shortens a string down to the number of words passed as the argument. If the specified number of words is less than the number of words in the string, an ellipsis (…) is appended to the string. And Custom ellipsis can be also applied as truncate.
Input:
{{"Ground control to Major Tom."|truncatewords:3}}
Output:
Ground control to...
uri_escape / xml_escape
Input:
{{"foo, bar \baz?"|uri_escape}}{{"<p>Hi Jekyll</p>"|xml_escape}}
Output:
foo,%20bar%20%5Cbaz?
<p>Hi Jekyll</p>
url_encode
Converts any URL-unsafe characters in a string into percent-encoded characters.
divided_by divides a number by the specified number. The result is rounded down to the nearest integer (that is, the floor) if the divisor is an integer.
divided_by produces a result of the same type as the divisor — that is, if you divide by an integer, the result will be an integer. If you divide by a float (a number with a decimal in it), the result will be a float.
Creates an array of values by extracting the values of a named property from another object.
Input:
{%assignmy_array="a,b,c"|split:","%}{%assignmy_array=my_array|push:'d'%}{{my_array|array_to_sentence_string}}
Output:
a, b, c, and d
reverse
Reverses the order of the items in an array. Although reverse cannot reverse a string, but you can split a string into an array, reverse the array, and rejoin it by chaining together filters:
Input:
{%assignmy_array="apples, oranges, peaches, plums"|split:", "%}{{my_array|reverse|join:", "}}{{"Ground control to Major Tom."|split:""|reverse|join:""}}{{"Ground control to Major Tom."|split:" "|reverse|join:" "}}
Output:
plums, peaches, oranges, apples
.moT rojaM ot lortnoc dnuorG
Tom. Major to control Ground
size
Return the size of an array or string.
sort
Sorts items in an array by a property of an item in the array. The order of the sorted array is case-sensitive.
Select all the objects in an array where the key has the given value.
date
Converts a timestamp into another date format. The format for this syntax is the same as strftime. It also works on strings if they contain well-formatted dates:
Input:
{{page.date|date:"%a, %b %d, %y"}}{{"August 20, 2016"|date:"%b %d, %y"}}
Output:
Sat, Aug 20, 16
Aug 20, 16
filter
explain
output
%a
Abbreviated weekday
Sun
%A
Full weekday name
Sunday
%b
Abbreviated month name
Jan
%B
Full month name
January
%c
Preferred local date and time representation
Fri Jan 29 11:16:09 2016
%d
Day of the month, zero-padded
05
%-d
Day of the month
5
%D
Formats the date
29/01/16
%e
Day of the month
3
%F
Returns the date in ISO 8601 format
2016-01-29
%H
Hour of the day, 24-hour clock
07
%I
Hour of the day, 12-hour clock
07
%j
Day of the year
017
%k
Hour of the day, 24-hour clock
7
%m
Month of the year
04
%M
Minute of the hour
13
%p
Meridian indicator uppercase
AM
%P
Meridian indicator lowercase
pm
%r
12-hour time
01:31:43 PM
%R
24-hour time
18:09
%T
24-hour time with seconds
18:09:13
%s
Number of seconds since 1970-01-01 00:00:00 UTC
1452355261
%S
Second of the minute
05
%U
Week number of the current year, starting with the first Sunday as the first day of the first week
03
%W
Week number of the current year, starting with the first Monday as the first day of the first week
09
%w
Day of the week. Sunday is 0
5
%x
Preferred representation for the date
05/11/15
%X
Preferred representation for the time
17:15:31
%y
Year without a century
16
%Y
Year with century
2016
%Z
Time zone name (PST)
%%
Literal % character
Besides, date_to_long_string convert a date to long format; date_to_long_rfc822 convert a Date into RFC-822 format; date_to_string convert a date to short format and date_to_xmlschema convert a Date into ISO 8601 format.
Input:
{{page.date|date_to_long_string}}{{page.date|date_to_rfc822}}{{page.date|date_to_string}}{{page.date|date_to_xmlschema}}
Output:
20 August 2016
Sat, 20 Aug 2016 00:00:00 +0800
20 Aug 2016
2016-08-20T00:00:00+08:00
SmartyPants is a free web publishing plug-in for Movable Type, Blosxom, and BBEdit that easily translates plain ASCII punctuation characters into “smart” typographic punctuation HTML entities. ↩
THE END
Ads by Google
林宏
Frank Lin
Hey, there! This is Frank Lin (@flinhong), one of the 1.41 billion . This 'inDev. Journal' site holds the exploration of my quirky thoughts and random adventures through life. Hope you enjoy reading and perusing my posts.
JavaScript is a very function-oriented language. As we know, functions are first class objects and can be easily assigned to variables, passed as arguments, returned from another function invocation, or stored into data structures. A function can access variable outside of it. But what happens when an outer variable changes? Does a function get the most recent value or the one that existed when the function was created? Also, what happens when a function invoked in another place - does it get access to the outer variables of the new place?
IKEv2, or Internet Key Exchange v2, is a protocol that allows for direct IPSec tunnelling between networks. It is developed by Microsoft and Cisco (primarily) for mobile users, and introduced as an updated version of IKEv1 in 2005. The IKEv2 MOBIKE (Mobility and Multihoming) protocol allows the client to main secure connection despite network switches, such as when leaving a WiFi area for a mobile data area. IKEv2 works on most platforms, and natively supported on some platforms (OS X 10.11+, iOS 9.1+, and Windows 10) with no additional applications necessary.
IBM Cloud CLI allows complete management of the Cloud Functions system. You can use the Cloud Functions CLI plugin-in to manage your code snippets in actions, create triggers, and rules to enable your actions to respond to events, and bundle actions into packages.