控制流程

控制流程標籤會建立條件,以決定是否執行 Liquid 程式碼區塊。

if

僅在特定條件為 true 時執行程式碼區塊。

輸入

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

輸出

These shoes are awesome!

unless

if 相反 – 僅在不符合特定條件時執行程式碼區塊。

輸入

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

輸出

These shoes are not awesome.

這相當於執行以下操作

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

elsif / else

ifunless 區塊中新增更多條件。

輸入

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

輸出

Hey Anonymous!

case/when

建立 switch 語句,當變數具有指定值時執行特定的程式碼區塊。case 初始化 switch 語句,而 when 語句定義各種條件。

when 標籤可以接受多個值。當提供多個值時,當變數符合標籤內的任何值時,將傳回運算式。以逗號分隔清單提供值,或使用 or 運算子分隔。

case 結尾的可選 else 語句,會在沒有符合任何條件時提供要執行的程式碼。

輸入

{% 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 %}

輸出

This is a cake