The basics of Liquid, Shopify's theme development language
This article is an introductory book by our company on Shopify, Hello Shopify Themes: A Guide to Shopify Theme Development Here's an excerpt from .
In this section, we will explain the grammar of Liquid.
If you’ve read this book in such order, do you already know that Liquid syntax is primarily used to retrieve Shopify content data and display it on the page?
The contents introduced in this section are as follows.
- Fundamentals of Liquid
- Liquid object
- liquid tag
- liquid filter
We don’t introduce all of the Liquid tags or objects available today, as there are too many and Shopify updates will likely increase even after this book is published.
We will also introduce how to read the official document, so please use it together.
Contents [ hidden display ]
How to read and find official documents
First, the Shopify official Liquid documentation includes:
Liquid reference
https://shopify.dev/api/liquid
There are only English documents at the moment, but if you don’t like English because of its high information, speed and accuracy, please use translation extension tool in your browser.
In addition to the basic syntax of Liquid, there is also information about Shopify-specific Liquid objects, Liquid tags and Liquid filters.
In addition to the above document, there is also an official website of Liquid.
Shopify-specific information is not available, but the general tag filters for Liquid are covered and can be useful if you refer to them.
search for English information
Shopify has a lot of updates, so the structure and URL of documents are relatively different; it’s easier to find the information you need when you search from outside than remember where in your document is.
Since information for merchants is easy to come out in Japanese search, let's make a habit of searching in English about technical information.
Shopify product object haha. Shopify date filter It is good to search by "What content data, what function do you want to know?"
Fundamentals of Liquid Notation (Type, Operator, True and False Values, Variables, Whitespace Control)
First, we will introduce the basic grammar of Liquid.
mold
The Liquid object has six data types as shown below:
- String
- Number
- Boolean
- Array
- Nil
- EmptyDrop
There are many familiar ones for those who have touched other programming languages such as JavaScript.
We have summarized some simple features in the following table, and you don't need to specify a data type when declaring variables.
| mold | description |
|---|---|
| String | Strings. 'sample' or "sample" enclose with quotation marks, as of) |
| Number | a series of numbers that can perform quadratic operations with formula filters) |
| Boolean | True and false. true or false |
| Array | Arrays. You can change the output by passing an array filter |
| Nil | An empty value returned if no code output results are present. The output on Liquid is blank |
| EmptyDrop | an object that is returned if nothing is stored in the object accessed) |
type transformation
Liquid type conversion is done via a Liquid filter (see below).
The following example is a Liquid filter that converts the string "2022" to number columns.
{{ "2022" | abs }}operator
The comparison operators that can be handled with Liquid are as follows:
| operator | Meaning |
|---|---|
== |
equal |
!= |
be not equal to |
> |
bigger |
< |
smaller |
>= |
above |
<= |
below |
or |
condition A or condition B |
and |
Condition A and condition B |
contains |
* Described later |
just the logical operator. or in and And because English appears, touching JavaScript and Liquid at the same time tends to be confusing. && It's not...
and as a special operator contains This will determine if a given string exists in an array of strings and strings, and return true/false.
The following code outputs the name of an online store only if the page title does not contain a name for the online store:
{% unless page_title contains shop.name %}
{{ shop.name }}
{% endunless %}true and false value
If a non-Boolean type, such as a string, is used in the conditional tag nil all the other types true it's treated as an empty string EmptyDrop The same is true for types.
If you want to perform conditional branching when the object is empty, let's decide by whether it is blank or not.
// page.descriptionが空でなければ、説明文を出力する
{% if page.description != blank %}
<p>{{ page.description }}</p>
{% endif %}variable
Liquid tag described later {% assign %} or {% capture %} You can create your own variables in a Liquid file using tags, and you can treat them as Liquid objects.
scope of a variable
Variables created in a Liquid file are basically only available within that file, and cannot be accessed to variables made from another file.
* Exceptionally, a snippet file {% render %} If the tag has a parameter, you can use the value of the variable in the read source file.
Note: overwrite of variables
The Liquid object pre-defined by Shopify is also a Liquid variable whose internal values are mutable.
When you create a variable with the same name as your defined Liquid object, its internal values are overwritten.
<p>ストアの名称(上書き前):{{ shop.name }}</p>
//Liquidオブジェクトのshopを同名変数で上書き
{% assign shop = '上書きテスト' %}
<p>ストアの名称(上書き後):{{ shop.name }}</p>
This is the output result; after overwriting a shop object no longer has its name attribute, so it's empty.
<p>ストアの名称(上書き前):Sample Store</p> <p>ストアの名称(上書き後):</p>
The value will only be overridden in the Liquid file that created this variable, but you should be careful not to overwrite it unintendedly.
blank control
In the Dawn theme, many Liquid tags are described in a form that contains hyphens.
This is a notation for not outputting unnecessary blanks on HTML.
Liquid is: {% if customer %} Even if a tag doesn't output text directly on the page, such as "By default", empty lines are exported to HTML. It is hard to notice when you look at it in browser developer tools, but you can see well by displaying the source of the whole page.
{%- if customer -%} It is possible to prevent the output of empty lines by describing it as ".
That’s the basic explanation for Liquid.
Liquid object
The Liquid object is cool in double {{ }} The Shopify content data is exported to the page by surrounding it with various types of objects, some of which change their behavior depending on what Liquid file you are writing.
The following shows a product title that is appropriate for each product page product It is an object. product The object is: title In addition to attributes, description haha. price It has a variety of attributes, such as:
{{ product.title }} As mentioned above, this section does not touch on all of the objects and will be explained in a limited way.
For more information on individual objects, see the Shopify official documentation as well.
Liquid objects
https://shopify.dev/api/liquid/objects
object handle
Shopify’s content (product, fixed page, blog, blog post menu) has a handle that identifies each of them; in the content with pages, the value of the handle will be the URL as it is.
For example, the handle value of a product with the following URL special-coffee Yes.
http://sample-store.myshopify.com/products/special-coffee
By combining objects and handles that contain multiple contents, you can output the necessary content properly.
The following is an object that holds all the items in a store all_products from the handle value. special-coffee have product The sample code to access the object.
{{ オブジェクト.ハンドル値.属性 }} or {{ オブジェクト["ハンドル値"].属性 }} I will describe it.
{{ all_products.special-coffee.title }}
{{ all_products["special-coffee"].title }}global object
Global objects can be used in any Liquid file within the theme.
In the development of themes, we introduce those that are frequently used.
| object | Characteristics |
|---|---|
all_products |
all of the stores product array containing an object |
articles |
all of the stores article array containing an object |
blogs |
all of the stores blog array containing an object |
cart |
cart information in the store |
collections |
all of the stores collection array containing an object |
current_tags |
an array of tags that are returned depending on the source template, such as a product or article) |
customer |
Customer information logged in to the store (no return anything when not logged in) |
linklists |
all menu lists on the store linklist array containing an object |
pages |
all of the stores page array containing an object |
shop |
information about a store, such as name or address) |
settings |
information about the theme setting |
If you combine it with the object handle described above, only necessary data can be retrieved and handled.
product object
The most frequent thing to deal with in the development of a theme is this storing commodity information. product It is an object.
In the product page template, you can automatically access information about that item; if it is used on another page such as a fixed page or blog post collection objects, all_products Combine it with an object to access the goods you need.
It has nearly 40 attributes and you don't have to remember all of them, but the most frequently used properties are useful if you keep track of the specifications in your official documentation.
The product object
https://shopify.dev/api/liquid/objects/product
The following table is an example of a high usage attribute.
| attribute | Characteristics |
|---|---|
product.available |
determine whether a product is available or not and return true/false |
product.description |
product description |
product.featured_media |
main image of a product |
product.price |
the lowest price between variations of goods) |
product.tags |
an array of products' tag lists |
product.title |
product title |
product.type |
type of goods |
product.url |
relative pass URL for a product |
product.variants |
an array of variations in a product |
Other useful objects
For other useful Liquid objects, we'll say: 4-2. Implementation of each page The following is an example of the object that you want to understand in particular.
line_item object
line_item an array of objects representing goods in a cart cart.item an arrangement of items ordered) order.line_item Represents the individual goods in an object.
This object is used not only when customizing the cart, but also in the purchase completion notification mail to customers.
section object/block object
It is a unique object that can only be used in section files and snippet files rendered within the section files.
Here we will dig deeper in the next section "4-4.Theme File Explanation".
liquid tag
A Liquid tag is a description of the programming logic used in a Liquid file. {% %} It is described in.
It is roughly divided into the following four categories.
- conditional determination tag
- iterative output tag
- theme tag
- variable tag
conditional determination
Create a conditional decision like if statement during Liquid.
if
It outputs and executes internal code only if the condition determination result is true.
{% if product.title == 'Hello Shopify Themes' %}
<p>Enjoy Shopify Development!</p>
{% endif %}unless
Contrary to the if statement, outputs and executes internal code when conditional determination results are false.
{% unless product.available %}
<p>この商品は購入できません。</p>
{% endunless %}else / elsif
In the if/if statement, we will write it when adding more conditional judgments: If you are used to JavaScript {% else if %} not {% elsif %} Please note that it is.
{% if product.type == 'コーヒー' %}
<a href="/collections/sweets_coffee">コーヒーに合うお菓子のセット</a>
{% elsif product.type == '紅茶' %}
<a href="/collections/sweets_tea">紅茶に合うお菓子のセット</a>
{% else %}
<a href="/collections/other">その他のおすすめ商品</a>
{% endif %}case / when
a more complex criterion switch as a tag to create sentences {% case %}/{% when %} And there's this. In Dawn, sections/main-product.liquid It is used in such as.
If you are interested, please refer to the official documentation.
Control flow tags
https://shopify.dev/api/liquid/tags/control-flow-tags#case-when
iterative output
Create a recurring for statement during Liquid. It is often used on the product list page or blog post list page. The output limit per loop is up to 50. If there are more than one loop target, then this theme tag will be described later. {% paginate %} Split the page by ".
In addition, as with the conditional decision sentence: {% else %} You can add the output result if loop length is 0.
{% for item in collection.products %}
{{ product.title }}
{% else %}
<p>条件に一致する商品がありません。</p>
{% endfor %}more complex loop processing
{% for %} In a tag, the loop iteration is stopped midway {% break %} skip along the way through tags or iterations) {% continue %} Tags are also available.
There are also parameters that specify the start/end position of a loop and its iterative order. limit A sample code that specifies the end position of a loop with parameters.
//コレクション内の商品数に関わらず、2点までしか出力しない
{% for product in collection.products limit:2 %}
{{ product.title }}
{% endfor %}list of parameters
| parameter | description |
|---|---|
limit |
Specifies the end of loop position |
offset |
specify the loop start position |
(x...y) |
Specify a range of numerical loops, x/y is an arbitrary number. {% for i in (3..5) %} |
reversed |
reversing the loop order |
Leveraging forloop objects
{% for %} as a Liquid object that is only used in the tag forloop There is.
Since there is an attribute that returns true only for the first and last item in a loop, please use it.
The following is a sample code that grants an additional class only to the first block in a loop of block objects that make up the slider:
{% for block in section.blocks %}
<div class="slide {% if forloop.first == true %}firstSlide{% endif %}">
//中略
</div>
{% endfor %}About cycle / tablerow
in this book, i'm done with it. there are other repetitive tags {% cycle %} and {% tablerow %} If you are interested, please refer to the official documentation.
Iteration tags
https://shopify.dev/api/liquid/tags/iteration-tags
theme tag
There are various types of theme tags that specify logic related to the subject, and we will introduce those that are frequently used in this section.
Comments
Write a comment in the Liquid file.
{% comment %}〜{% endcomment %} The contents described in between will not be output or executed.
rendering (not comparable)
Tags responsible for rendering Liquid files. {% section 'セクションファイル名' %} and {% render 'スニペットファイル名' %} There is.
Both are explained in detail in the section file and snippet file part of "Theme File Explanation" next section.
pagination
The maximum number of outputs per loop is 50, which I mentioned earlier in the explanation for "repetitive output".
In the product list and blog post list page, loop target easily breaks 50 (it is more common to separate pages with fewer than 50 in the first place). {% for %} tag. {% paginate %} it's surrounded by tags. by By passing a parameter, you can split the loop result by the specified number.
The following code is an example of adding pagination if you want to output 10 products per page, and the output results are divided into two pages or later.
{% paginate collection.products by 10 %}
{% for product in collection.products %}
(商品情報)
{% endfor %}
{% if paginate.pages > 1 %}
{{ paginate | default_pagination }}
{% endif %}
{% endpaginate %}{{ paginate | default_pagination }} outputs the default pagination in Shopify.
The unique pagination is a Liquid object paginate You can create an object using it.
form
There is an opportunity to touch many forms in the development of themes, such as purchase forms and account creation forms. {% form %} If you use Shopify, the appropriate HTML element will be output for each form type available on Shopify.
The following is a sample code for outputting the customer login form:
{% form 'customer_login' %}
<div class="field">
<input type="email">
</div>
//その他、各項目のinput要素や、フォーム送信ボタンなど
{% endform %} The output results look like this: form in elements, as required by form) action It is automatically rendered in the form of attributes etc.
<form accept-charset="UTF-8" action="https://sample.myshopify.com/account/login" id="customer_login" method="post">
<input name="form_type" type="hidden" value="customer_login" />
<input name="utf8" type="hidden" value="✓" />
<div class="field">
<input type="email">
</div>
//その他、各項目のinput要素や、フォーム送信ボタンなど
</form> Shopify has many forms, so we won't cover everything in this book but if you want to add a new form within the theme and submit data: {% form %} Please refer to the tag documentation.
Theme tags (form description section)
https://shopify.dev/api/liquid/tags/theme-tags#form
variable tag
Create your own variable in the Liquid file.
{% assign 変数名 = 値 %} Or, {% capture 変数名 %}値{% capture %} It is possible to create it in the form of
The following code shows {% assign %} and {% capture %} This is an example of creating a variable using 'Target', and you can assign values again to the created variable.
//変数favoriteを作成
{% assign favorite = '猫' %}
//変数favorite_textを作成(favoriteの出力結果を含む)
{% capture favorite_text %}
<p>私は{{ favorite }}が好きです。</p>
{% endcapture %}
//変数favorite_textの出力
1:{{ favorite_text }}
//変数favoriteに値を再代入
{% assign favorite = 'りんご' %}
//変数favorite_textを再出力
2:{{ favorite_text }}
//変数favoriteを再出力
3:<p>私は{{ favorite }}が好きです。</p>The output result is as follows.
1:<p>私は猫が好きです。</p>
//変数favorite再代入後だが、{% capture %}作成時の変数favorite_textの値が表示される
2:<p>私は猫が好きです。</p>
//変数favoriteに再代入した値が表示される
3:<p>私はりんごが好きです。</p>For the specification of variables in Liquid, see also below as it is described above on the basis of Liquid notation.
About the increment / decrement
as a tag that allows you to create and deduct numerical variables {% increment %} and {% decrement %} This book does not give up, but if you are interested please refer to the official documentation.
Variable tags
https://shopify.dev/api/liquid/tags/variable-tags
liquid filter
Liquid filter is a description for processing output contents. {{ 加工元オブジェクト | フィルタ指定 }} like a separator in a double cuckoo | It is also possible to combine multiple filter specifications, and the type conversion of data (string → number column etc. )
The following is a sample code for outputting the blog post date in "2022.01.01" format.
{{ article.published_at | date: '%Y.%m.%d' }}If you change the filter designation, only output results can be processed differently with the original value as is: The following code will print out the post date in "January 1, 2022" format.
{{ article.published_at | date: '%Y年%-m月%-d日' }}The Liquid filter classification described in the document as of February 2022 is: Since then, more available filters have been increased.
| filter segmentation | Characteristics |
|---|---|
| Array filters | an array of processing filters |
| Color filters | Processing Filter for CSS Color Information |
| Font filters | WORKING FILTER FOR FLOOR OBJECT |
| HTML filters | A filter that generates HTML elements |
| Math filters | several-row processing filter |
| Media filters | URL Acquisition and HTML Output Filter for Product Image |
| Metafield filters | MACHINE FILTER OF METAFIELD |
| Money filters | processing filter based on store currency settings |
| String filters | character string processing filter |
| URL filters | URL EQUIPMENT AND OUTPUT/WORKING FILTER FOR LINK ELEMENT |
| Additional filters | Other common processing filters |
In this book, we will introduce some excerpts.
Hosted file filters (formerly URL filters)
Shopify distributes assets such as images via CDN (Content Deliver Network to improve loading speed), and with the Hosted file filter, you can get and output URLs on the CDN of that asset.
Other than that, you can also output links in the theme and links to collections according to your preference.
The next thing I'll show you assets/theme.css This is the code to output a URL.
{{ 'theme.css' | asset_url }}asset_url There are about 20 other notations, so if you want to get or output some kind of URL, please refer to the Hosted file filter document.
Hosted file filters
https://shopify.dev/docs/api/liquid/filters/hosted_file-filters
image filter
from just outputting an image URL to HTML. <img> There are also various filters for the image output, up to those that output tags.
so here's a favicon image. <img> This is a sample code for outputting as tags. image_url filters. image_tag You can see that the filter is used.
{{ settings.favicon | image_url: width: 200 | image_tag: srcset: nil, loading: lazy }} * As a division, URL filters are used. image_url and the HTML filter. image_tag It is combined.
The output results are as follows:
<img
src="//cdn.shopify.com/s/files/xxxxxxxxxxxx/files/favicon.png?v=xxxxxxxxxx&width=200"
width="200"
height="200"
loading="lazy"> Image URL with image_url filter //cdn.shopify.com/s/files/xxxxxxxxxxxx/files/favicon.png?v=xxxxxxxxxx&width=200 get it, and image_tag an additional attribute by passing through a filter) loading="lazy" include <img> The tag is output.
image_url filters. image_tag Both filters provide a number of parameters to process the output results, so please refer to our official documentation if necessary.
date filter
The date filter converts the timestamp value to other date formats and outputs the following code output, for example: 2022.01.01 It's like that.
{{ article.published_at | date: '%Y.%m.%d' }} in the parameters and sample code of a filter. '%Y.%m.%d' The part is Ruby. strftime Please write along with the method.
strftime You can check the official documentation of Ruby or the format conversion site.
Ruby Official Strftime Documentation
https://ruby-doc.org/core-3.0.2/Time.html#method-i-strftime
strftime conversion site
http://www.strfti.me/
Note: Getting the current time in a date filter
to display the current date and time now or today and date An example of combining filters may be introduced.
{{ "now" | date: "%Y-%m-%d %H:%M" }} This looks like it's outputting the current time for users, but to be exact: Time when a page is generated from Liquid on the Shopify server So, although it depends on the cache situation, there will be a time lag of minutes to hours from the actual current time.
If you want to integrate strict current time into your logic, consider using JavaScript together.
date – Liquid template language (explanation from Liquid's official website)
https://shopify.github.io/liquid/filters/date/
Click here to purchase the introductory book on Shopify theme development that we produced at our company.
We do not have any plans for printing after the sale at this time, so if you would like to read a printed book please pick us up as soon as possible.
- Author: Sayaka Kawashima
- Publishing: Non-standard world, Inc.
- Number of pages: B5, 248
- Price: 3,850 yen (tax included) * Packed with PDF version, free shipping