如何在不重复缩进代码的情况下在HAML中执行if / else

根据用户是否登录,我想打印另一种%body标签。

这就是我目前的做法:

- if defined? @user %body(data-account="#{@user.account}") %h1 Welcome -# all my content - else %body %h1 Welcome -# all my content 

正如您所看到的,那里有很多重复的代码。 我怎么能消除这个? 我已经尝试过以下方法:

 - if defined? @user %body(data-account="#{@user.account}") - else %body %h1 Welcome -# all my content 

不幸的是,这不起作用,因为HAML将其解释为好像%h1和内容是else语句的一部分,当然它们不是。

关于如何解决这个问题的任何想法? 我一直在遇到这个问题,所以我无法想象它没有一个简单的解决方案。

 !!! - @user = "jed" #=> stubbing out an instance %html %head - string = defined?(@user) ? "#{@user}" : nil #=> for demo only, wrap this in a helper method %title{'data-account' => string} %body =yield 

我不认为您可以避免缩进问题,因为HAML自动分配“结束”语句的方式,但您可以将if语句推送到body标签本身 –

 %body{:data_account => (defined? @user ? @user.account : nil)} 

而不是

 %body(data-account="#{@user.account}") 

不是非常漂亮,但比重复整个街区更难看!

HAML优雅的解决方案是助手

 class ApplicationHelper... def body_for_user(user, &blk) return content_tag(:body, :'data-account' => user.account, &blk) if user content_tag(:body, &blk) end end 

上面描述的三元运算符对于这种特殊情况来说已经足够了,但对于更复杂的事情,可以打破帮助者。

哦,要使用它,在你的视图中将%body(...)更改为= body_for_user @user do

写一个这样的帮手:

 def body_attributes {}.tap do |hash| hash[:data] = {} hash[:data][:account] = @user.account if @user # add any other attributes for the body tag here end end 

然后从body元素调用helper:

 %body{ body_attributes } %h1 Welcome -# all my content 

对于任何寻找HAML的Ruby if / else问题答案的人来说,这就是我如何解决它:

 %tr{ id: (line_item == @current_item) ? "current_item" : nil } %td= button_to '-', decrement_line_item_path(line_item), method: :put, remote: true %td #{line_item.quantity}× %td= line_item.product.title %td.item_price= number_to_currency(line_item.total_price) 

我通常在控制器上设置@@ menu变量,然后在启用bootstrap的layout.haml中定义:

  ... %body .navbar.navbar-fixed-top .navbar-inner .container %a.btn.btn-navbar{"data-target" => ".nav-collapse", "data-toggle" => "collapse"} %span.icon-bar %span.icon-bar %span.icon-bar %a.brand{:href => "/"} AwesomeApp .nav-collapse %ul.nav %li{:class => @@menu == 'home' && :active} %a{:href => "/"} Home %li{:class => @@menu == 'about' && :active} %a{:href => "https://stackoverflow.com/about"} About %li{:class => @@menu == 'contact' && :active} %a{:href => "https://stackoverflow.com/contact"} Contact 

当我将@@ menu设置为’about’时,它将呈现: