在条件语句(if、unless)中使用时,某些 Liquid 值会被视为“true”,某些会被视为“false”。
在 Liquid 中,空值和布尔值 false 被视为 false;其他所有值都被视为 true。 例如,空字符串和空数组被视为 true。
{% assign empty_string = "" %}
{% if empty_string %}
<p>This will render.</p>
{% endif %}
必要时,使用特殊值 empty 测试空字符串和空数组。
{% unless page.title == empty %}
<h1>{{ page.title }}</h1>
{% endunless %}
使用特殊大小属性测试 Liquid 类型的大小。
{% if page.children.size > 0 %}
<ul>
{% for child in page.children %}
<li>{{ child.title }}</li>
{% endfor %}
</ul>
{% endif %}
总结
| Operator | 真 | 假 |
|---|---|---|
| 真 | × | |
| 假 | × | |
| Null | × | |
| String | × | |
| 空字符串 | × | |
| 0 | × | |
| 1, 3.14 | × | |
| 数组或词典 | × | |
| 空数组或词典 | × | |
| 对象 | × |