控制流
控制流标签创建条件,用于决定是否执行 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
在 if
或 unless
代码块中添加更多条件。
输入
<!-- 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