我有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
它可以有默认"短"文字或替代文字。对于一些推荐,我想在某些页面上使用替代文本,同时使用" short"别人的文字。
在我的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
结果如下:
我做错了什么?有没有办法使用检查数据是否存在的条件语句?
答案 0 :(得分:1)
defined?
does not really do what you want. You can just just leave it away, the if
will just evaluate to false
because the value will be nil
for alt
.
So just put
- ['tom','jeff','joel'].each do |person|
%blockquote
- if data.testimonials[person].alt
= data.testimonials[person].alt
- else
= data.testimonials[person].short
Or you could actually write it much shorter:
- ['tom','jeff','joel'].each do |person|
%blockquote
= data.testimonials[person].alt || data.testimonials[person].short
I don't really know for sure, why defined?
does not work, but generally you don't need the method to check for it, because undefined values will just give you a nil
in middleman.