跳到主要内容

条件标签

Conditional tags 定义决定 Liquid 代码块是否执行的条件。

if

当特定条件为 true 时渲染表达式。

{% if condition %}
expression
{% endif %}
  • condition:要评估的条件。
  • expression:条件满足时要渲染的表达式。
{% if product.compare_at_price > product.price %}
This product is on discount!
{% endif %}
{
"product": {
"compare_at_price": "18.88",
"price": "12.88"
}
}
This product is on discount!

elsif

您可以使用 elsif tag 检查多个条件。

{% if product.type == 'Seafood' %}
This is a seafood type!
{% elsif product.type == 'Fruit' %}
This is a fruit type!
{% endif %}
{
"product": {
"type": "Fruit"
}
}
This is a fruit type!

else

允许您指定在没有其他条件满足时执行的默认表达式。

您可以将 else tag 与以下 tags 配合使用:

{% else %}
expression
  • expression:在没有其他条件满足时要渲染的表达式。
{% if product.available %}
This product is available!
{% else %}
This product is sold out!
{% endif %}
{
"product": {
"available": false
}
}
This product is sold out!

unless

除非特定条件为 true,否则渲染表达式。

📘 提示

if tag 类似,您可以使用 elsifunless tag 添加更多条件。

{% unless condition %}
expression
{% endunless %}
  • condition:要评估的条件。
  • expression:在条件不满足时要渲染的表达式。
{% unless product.has_only_default_variant %}
Variant selection functionality
{% endunless %}
{
"product": {
"has_only_default_variant": false
}
}
Variant selection functionality

case

根据特定变量的值渲染特定表达式。

{% case variable %}
{% when first_value %}
first_expression
{% when second_value %}
second_expression
{% else %}
third_expression
{% endcase %}
  • variable:您要基于其进行 case 判断的变量名称。
  • first_value:要检查的特定值。
  • second_value:要检查的特定值。
  • first_expression:当变量值匹配 first_value 时渲染的表达式。
  • second_expression:当变量值匹配 second_value 时渲染的表达式。
  • third_expression:当变量值不匹配任何条件时渲染的表达式。
{% case product.type %}
{% when 'Seafood' %}
This is a seafood type.
{% when 'Fruit' %}
This is a fruit type.
{% else %}
This is a food.
{% endcase %}
{
"product": {
"type": "Fruit"
}
}
This is a fruit type.