1

I have a Middleman data file data/testimonials.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

It can have either default "short" text or an alternative text. For some testimonials, I want to use alternative text for some pages, while using "short" text for others.

In my test.haml I am trying to write HAML statement that checks whether alternative text exists. If it does, it should be inserted; if it doesn't, the standard text should be used instead.

Following example shows that data.testimonials[person].alt properly refers to information from data, because it can be inserted manually. However, when I use the same variable in if defined? statement, it never returns 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

The result is this:

What am I doing wrong? Is there any way to use a conditional statement that checks whether data exists?

4

1 回答 1

1

defined?并没有真正做你想做的事。你可以把它放在if一边,false因为它的值将是nilfor alt

所以只要放

- ['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

我真的不确定,为什么defined?不起作用,但通常你不需要检查它的方法,因为未定义的值只会给你一个nil中间人。

于 2017-08-04T12:41:49.240 回答