Ruby 如果定义了HAML?评估中间人数据文件中是否存在条目的语句

Ruby 如果定义了HAML?评估中间人数据文件中是否存在条目的语句,ruby,if-statement,haml,middleman,text-database,Ruby,If Statement,Haml,Middleman,Text Database,我有一份数据/证明。yaml: tom: short: Tom short alt: Tom alt (this should be shown) name: Thomas jeff: short: Jeff short alt: Jeff alt (this should be shown) name: Jeffrey joel: short: Joel short (he doesn't have alt) name: Joel 它可以有默认的“短”文本

我有一份
数据/证明。yaml

tom:
  short: Tom short
  alt: Tom alt (this should be shown)
  name: Thomas

jeff:
  short: Jeff short
  alt: Jeff alt (this should be shown)
  name: Jeffrey

joel:
  short: Joel short (he doesn't have alt)
  name: Joel
它可以有默认的“短”文本或替代文本。对于一些推荐书,我想对一些页面使用替代文本,而对其他页面使用“短”文本

在我的
test.haml
中,我试图编写检查是否存在替代文本的haml语句。如果有,则应插入;如果没有,则应使用标准文本

下面的示例显示,
data.estimationals[person].alt
正确地引用了数据中的信息,因为它可以手动插入。然而,当我在
if defined?
语句中使用相同的变量时,它永远不会返回true

Not-working 'if' way, because 'if defined?' never evaluates to true:
- ['tom','jeff','joel'].each do |person|
    %blockquote
        - if defined? data.testimonials[person].alt
            = data.testimonials[person].alt
        - else
            = data.testimonials[person].short

Manual way (code above should return exactly this):
- ['tom','jeff'].each do |person|
    %blockquote
        = data.testimonials[person].alt

- ['joel'].each do |person|
    %blockquote
        = data.testimonials[person].short
结果是:


我做错了什么?有没有办法使用条件语句来检查数据是否存在?

已定义?
并不能真正满足您的需要。您可以不使用它,
if
将计算为
false
,因为
alt
的值将为
nil

所以就放

- ['tom','jeff','joel'].each do |person|
    %blockquote
        - if data.testimonials[person].alt
            = data.testimonials[person].alt
        - else
            = data.testimonials[person].short
或者你可以写得更短:

- ['tom','jeff','joel'].each do |person|
    %blockquote
        = data.testimonials[person].alt || data.testimonials[person].short

我真的不知道为什么
已定义?
不起作用,但通常不需要方法来检查它,因为未定义的值只会在middleman中给你一个
nil

这非常有效,我喜欢较短的版本!现在我可以介绍更多的变体,因为此解决方案适用于任意数量的OR语句。@Rafal欢迎您,我只希望我能理解,为什么定义了
不起作用。这有点好,它不起作用,当时我还不知道这个较短的版本:)我以为我遗漏了一些关于Ruby条件句如何工作的内容,但显然这只是Middleman中的一个bug。