使用haml時,我有以下問題。haml兩個空格問題
首先我想檢查一個變量,然後渲染其他東西,但它仍然應該嵌套。
讓我解釋一下
代碼:
.a
.b
gives: <div class=a><div class=b></div></div>
當我使用HAML如果別的,我不能嵌套.B內.A:
- if id == 3
.a{style => 'xxx'}
- else
.a{style => 'yyy'}
.b <-- 2 spaces, otherwise it fails. but 2 spaces are causing the following issue:
的問題是,因爲在haml中沒有結束,我不知道如何將.b放在.a div中,在這兩種情況下(如果id == 3,否則)。
作爲一個活生生的例子:
- if home != nil
.home
home.id
- else
.home
empty
- end <--- can't use
- if room != nil <-- without end, this will be executed only if home == nil but I wan't this to be executed always
room.id
- else
empty
因爲HAML好好嘗試一下支持末端,我無法使用它。如果我不使用它,haml會自動關閉div,因爲它們在同一行中,因此它們會自動關閉div :)
將變量與nil進行比較或僅在變量爲nil時執行某些操作的示例是隻是一個例子。我正在尋找一種解決方案,解決這個問題之後縮進,所以它適用於整個聲明。
有類似的問題:HAML: Indenting if/else statements with common content
所以,你的情況,你會做這樣的:
.a{ :style => id == 3 ? 'xxx' : 'yyy' }
.b
編輯: 在if... elsif... elsif...
情況下,你可以編寫自己的助手:
.a{ :style => select_style(variable) }
.b
#helper method
def select_style(val)
case val
when "3"
"xxx"
when "4"
"yyy"
else
"zzz"
end
end
當然,你可以用haml編寫它,但它會很醜陋:
- if id == "3" then val="xxx"
- elsif id == "4" then val="yyy"
- else val="zzz"
.a { :style => val }
.b
HAML有它的優點,但它的缺點中的一個的例子。
編輯
或者你可以去瘋了,不喜歡:
.a{:style => if var == "3" then "xxx" elsif var == "4" then "yyy" else "zzz" end}
什麼,如果我有如果,ELSIF×10? –
@ user665967,我已經更新了答案。 –
確定這有幫助,但不是在這種情況下。 我真正擁有的是,如果存在特殊變量,則顯示一個div。如果它不,展現另一種與價值觀: - 如果@ user.id == '1' .mydivname - 其他 .mydivname {:ID => @ street.name} 之後,我希望能有另一div中的.mydivname: .anotherdiv –