2017-08-04 20 views
1

是否存在進入我有一個Middleman data filedata/testimonials.yamlHAML如果定義?聲明中的評估數據中間人文件

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.testimonials[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 

結果是這樣的:

我在做什麼錯?有沒有辦法使用條件語句來檢查數據是否存在?

回答

1

defined?並不真正做你想做的。您可以將其忽略,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 

我真的不知道是肯定的,爲什麼defined?不起作用,但一般你不因爲未定義的值只會給你一箇中間人nil

+0

這個工程很好,我愛短版!現在我可以介紹更多的變體,因爲這個解決方案可以處理任何數量的OR語句。 – Rafal

+0

@Rafal歡迎你,我只是希望我明白,爲什麼'defined?'不起作用。 –

+0

它是一種很好的它不起作用,因爲那時我不知道這個更短的版本:)我以爲我錯過了一些關於Ruby條件是如何工作的,但顯然這只是Middleman中的一個錯誤。 – Rafal