LIquid 中的 Control flow 控制流程标签
Control flow 标签用于根据条件决定是否执行某些 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
块中添加更多条件。
输入
<!-- 如果 customer.name = "anonymous" -->
{% if customer.name == "kevin" %}
Hey Kevin!
{% elsif customer.name == "anonymous" %}
Hey Anonymous!
{% else %}
Hi Stranger!
{% endif %}
输出
Hey Anonymous!
case/when
创建一个开关语句,当变量有特定值时,执行某个代码块。case
用于初始化开关语句,when
用于定义条件。
when
标签可以接受多个值。当提供多个值时,只要变量匹配其中的任何一个值,都会执行相应的代码块。你可以将值用逗号分隔,或者使用 or
运算符。
else
语句是可选的,它提供了当没有条件满足时要执行的代码。
输入
{% assign handle = "cake" %}
{% case handle %}
{% when "cake" %}
这是 cake
{% when "cookie", "biscuit" %}
这是 cookie
{% else %}
这既不是 cake 也不是 cookie
{% endcase %}
输出
这是 cake