0

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}
4

2 回答 2

2

你也可以试试这个:

- if contition
  - attrs = { class: '..', id: '..' }
- else
  - attrs = { style: '...' }

.a{attrs}
  .b
于 2012-07-10T12:34:11.457 回答
1

有类似的问题: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}
于 2012-05-26T07:35:58.120 回答