目次

    Liquidとは

    Liquidは、Shopifyによって作成され、Rubyで記述されたオープンソースのテンプレート言語で様々なソフトウェアプロジェクトや企業で利用されています。 すべてのShopifyテーマのバックボーンであり、オンラインストアのページで動的なコンテンツをロードするために使用されています。

    Control flow tags(条件分岐)

    {% if product.title == ” %}など、{% %}で囲んで記述する条件分岐や繰り返しの記述、コードのブロックを実行するかどうかを決定する条件を作成します。
    基本的にはphpなどと同じようにif文(条件分岐)やfor文(繰り返し)などがあります。

    if

    特定の条件がtrueである場合にのみ、コードのブロックを実行します。

    【Input】
    {% if product.title == "Awesome Shoes" %}
    These shoes are awesome!
    {% endif %}

    trueなので、以下のように表示されます。

    【Output】
    These shoes are awesome!

    unless

    ifの反対、特定の条件が満たされない場合にのみコードのブロックを実行します。

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

    ifと記述が似ていますが、逆なので少しややこしいです。

    【Output】
    These shoes are not awesome.

    ifだと以下のような記述になります。

    【Input】
    {% if product.title != "Awesome Shoes" %}
    These shoes are not awesome.
    {% endif %}

    elsif/else

    ifまたはunlessブロック内に条件を追加します。
    ※ここでは名前がAnonymousがtrue

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

    【Output】
    Hey Anonymous!

    case/when

    変数に指定された値がある場合に、特定のコードブロックを実行するためのswitchステートメントを作成します。
    caseswitchステートメントを初期化し、whenステートメントはさまざまな条件を定義します。
    ケースの最後にあるオプションのステートメントは、いずれの条件も満たされない場合に実行するコードを提供します。

    【Input】
    {% assign handle = "cake" %}
    {% case handle %}
    {% when "cake" %}
    This is a cake
    {% when "cookie", "biscuit" %}
    This is a cookie
    {% else %}
    This is not a cake nor a cookie
    {% endcase %}

    【Output】
    This is a cake

    まとめ

    こちらはLiquidのテンプレのほんの1部になります。
    他にもタグが多数存在するので、チェックしてみてください。

    【参考サイト】
    Liquid template language
    Liquid reference

    PREV
    2022.06.10
    【自動】Pythonを使ってSlackに定期的にメッセージを投稿する
    NEXT
    2022.06.10
    Apollo ServerでGraphQLを動かしてみよう