更新日: 2021 / 02 / 12

Shopifyカスタマイズ初心者のための、Liquidの使い方

カテゴリー: Shopify

Shopifyではテンプレートに動的なコンテンツを出力するためのテンプレートエンジンとして、Liquidが使われています。

テンプレートエンジンはデータの出力を行うものなので、オブジェクト指向やSQLのような難しいことを覚えなくても簡単に使えます。

ここではLiquidの基本的な使い方を解説します。

Liquidで変数、配列、オブジェクトを作る方法

Shopifyではデータオブジェクトがあらかじめ定義されていますが、こちらで変数や配列を作ることも可能です。

// 変数
{% assign my_variable = false %}
{{ my_variable }}
// false

// 配列
{% assign fruits = ["orange", "apple", "peach"] %}
{{ fruits[0] }}
// orange

// オブジェクト
{% assign person = [{
  'name' : 'John Doe',
  'age' : '20'
}]; %}
{{ person[0].name }}
// John Doe

phpで"こんにちわ"+$worldのような変数を組み合わせた文字列はcaptureを使えば作れます。

// 文字列を含めた変数を作る
{% assign favorite_food = "pizza" %}
{% assign age = 35 %}
{% capture about_me %}
  I am {{ age }} and my favorite food is {{ favorite_food }}.
{% endcapture %}
{{ about_me }}

コンテンツなどをコメントアウトする場合はこちら。

{% comment %} and {% endcomment %}

Liquidのif文

Liquidの制御構文は他の言語とほぼ同じなので、あまり難しいところはありません。

if/elseの他に、条件が満たされなければ実行されるunless、条件によって処理を分けるcase/whenがあります。

// if/else
{% if customer.name == "kevin" %}
  Hey Kevin!
{% elsif customer.name == "anonymous" %}
  Hey Anonymous!
{% else %}
  Hi Stranger!
{% endif %}

// unless
{% unless product.title == "Awesome Shoes" %}
  These shoes are not awesome.
{% endunless %}

// case/when
{% 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 %}

演算子

if文で使う演算子は基本的に他の言語と同じ。phpでは&&がand、||がorになっています。

==	等しい
!=	等しくない
>	より大きい
<	より小さい
>=	以上
<=	以下
or	もしくは
and	且つ

Liquidのfor文

配列やオブジェクトの一覧を出力するfor文も他の言語と同様に使えます。

全て出力する以外に、条件を満たされれば停止するbreakや、上限を決めるlimitなどがあります。

詳しくはこちら

{% for product in collection.products %}
  {{ product.title }}
{% else %}
  The collection is empty.
{% endfor %}

// 特定の回数だけ回す
{% for i in (1..5) %}...{% endfor %}

// 作ったオブジェクトを回す
{% assign blog = [
  {
    'title' : 'blog title 1',
    'url' : 'https://blog.com/1'
  },
  {
    'title' : 'blog title 2',
    'url' : 'https://blog.com/2'
  }
]; %}
{% for article in blog %}...{% endfor %}