问题
When using haml I have following problem.
First I want to check one variable and after that render something else, but it still should be nested.
Let me explain
code:
.a
.b
gives: <div class=a><div class=b></div></div>
When I use haml if else, I can't nest .b inside .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:
The problem is, because there is no end in haml, I don't know how to put .b within .a div, in both situations (if id ==3, or else).
As an real live example:
- 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
because haml doens't support -end, I can't use it. If I don't use it, haml automatically closes div if I start to cehck 'room's values because these are in the same line :)
Example with comparing variable to nil, or doing something only if the variable is nil is just an example. I'm looking for a solution that solves such problem with indenting after else so it applies to the whole statement.
There are similar question: HAML: Indenting if/else statements with common content
So, in your case you would do like:
.a{ :style => id == 3 ? 'xxx' : 'yyy' }
.b
edited:
In case of if... elsif... elsif...
you can write your own helper:
.a{ :style => select_style(variable) }
.b
#helper method
def select_style(val)
case val
when "3"
"xxx"
when "4"
"yyy"
else
"zzz"
end
end
Of course you can write it all in haml, but it will be ugly:
- if id == "3" then val="xxx"
- elsif id == "4" then val="yyy"
- else val="zzz"
.a { :style => val }
.b
HAML has its advantages, but it is an example of one of the disadvantages.
edited
Or you can going mad and do like:
.a{:style => if var == "3" then "xxx" elsif var == "4" then "yyy" else "zzz" end}
回答1:
There are similar question: HAML: Indenting if/else statements with common content
So, in your case you would do like:
.a{ :style => id == 3 ? 'xxx' : 'yyy' }
.b
edited:
In case of if... elsif... elsif...
you can write your own helper:
.a{ :style => select_style(variable) }
.b
#helper method
def select_style(val)
case val
when "3"
"xxx"
when "4"
"yyy"
else
"zzz"
end
end
Of course you can write it all in haml, but it will be ugly:
- if id == "3" then val="xxx"
- elsif id == "4" then val="yyy"
- else val="zzz"
.a { :style => val }
.b
HAML has its advantages, but it is an example of one of the disadvantages.
edited
Or you can going mad and do like:
.a{:style => if var == "3" then "xxx" elsif var == "4" then "yyy" else "zzz" end}
回答2:
You could also try this:
- if contition
- attrs = { class: '..', id: '..' }
- else
- attrs = { style: '...' }
.a{attrs}
.b
来源:https://stackoverflow.com/questions/10763308/haml-two-spaces-issue