Jekyll / Liquid 条件基于 YAML 密钥的存在

问题描述 投票:0回答:1

我正在尝试根据 YAML 密钥是否存在来生成输出。给定

_data
中名为
users.yml
的文件:

 - name: Paul
   phone: 1234
 - name: John
 - name: George
 - name: Ringo
   phone: 4567

我循环遍历文件(使用

for user in site.data.users
,并尝试使用:

  • {% if user.phone == blank %} {{ "no phone number listed" }} {% endif %}
  • {% if user.phone == false %} {{ "no phone number listed" }} {% endif %}
  • {% if user.phone == empty %} {{ "no phone number listed" }} {% endif %}

但是对于没有电话号码的 2 个条目,这些都不会打印“未列出电话号码”。有没有办法做到这一点,或者我是否需要为那些没有空字符串的用户显式包含一个空字符串作为

phone
的值?

jekyll liquid
1个回答
0
投票

当没有键时,它的计算结果为

nil
,所以你应该有:

{% if user.phone == nil %} {{ "no phone number listed" }} {% endif %}

或者,您可以使用相反的检查:

{% unless user.phone %}{{ "no phone number listed" }}{% endunless %}

在这里您可以阅读有关 Liquid 中真值和假值的更多信息: https://shopify.github.io/liquid/basics/truthy-and-falsy/

© www.soinside.com 2019 - 2024. All rights reserved.