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.
Write a helper like this:
Then call the helper from the body element:
I usually set the @@menu variable at the controller, then in bootstrap-enabled layout.haml I define:
when I set @@menu to 'about' it will render:
HAML's elegant solution is helpers
The ternary operators described above are more than sufficient for this particular situation, but for more complex things, break out the helpers.
Oh, to use this, in your view change
%body(...)
to= body_for_user @user do
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 -
as opposed to
Not super-pretty, but less ugly than repeating the entire block!
For anybody looking for an answer to the Ruby if/else issue with HAML this is how I worked around it: