条件HAML - if else嵌套

17

我想要的是"if"和"else"里的内容都包含在#main-block中。

- if @transparency
  #content-inner{:style => "background: url(../../../images/illustrations/" + @transparency + ") no-repeat 88% 50%"}
- else 
  #content-inner
     #main-block

当前发生的情况是,如果定义了@transparency,则#main-block不会嵌套在#content-inner中。


看起来和这篇文章一样 - http://stackoverflow.com/questions/1451794/haml-if-else-error - 不过他们似乎没有得到除了重复之外的答案。 - Dr. Frankenstein
1个回答

22
你可以使用三元运算符来有条件地应用style属性:
#content-inner{ :style => @transparency ? "background: url(../../../images/illustrations/" + @transparency + ") no-repeat 88% 50%" : '' }
  #main-block

对于更为复杂的操作,例如操纵多个哈希属性,最好使用辅助方法或将公共内容移动到局部文件中。


1
刚看到你的答案,想补充一下,如果你必须在条件语句中评估 Ruby,可以像我做的那样:.request{ :class => (request.user_id == current_user.id) ? "highlight" : nil }。由于我的渲染方式(长话短说),我无法使用实例变量,因此我将 Ruby 评估在括号中,以查看此请求对象是否“belongs_to”当前用户,如果是,则将“highlight”类添加到 div 中。我觉得我应该分享这个小窍门,以防其他人还没有意识到。 - Robert Klubenspies

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接