Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an if/else in HAML without repeating indented code

Tags:

ruby

haml

Depending on if a user is signed in or not, I'd like to print a different kind of %body-tag.

This is how I currently do it:

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

As you can see there's a lot of duplicated code in there. How can I eliminate this? I already tried the following:

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

Unfortunately, this doesn't work since HAML interprets it as if the %h1 and the content is part of the else-statement, which of course they aren't.

Any ideas on how to solve this? I run in this problem all the time, so I can't imagine there isn't a simple solution for it.

like image 200
Marc Avatar asked Aug 11 '10 16:08

Marc


1 Answers

I don't think that you can avoid the indentation issue, because of the way HAML autoassigns the "end" statement, but you can instead push the if statement into the body tag itself -

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

as opposed to

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

Not super-pretty, but less ugly than repeating the entire block!

like image 186
bhaibel Avatar answered Oct 05 '22 08:10

bhaibel