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

Viewed 27563

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.

6 Answers

I usually set the @@menu variable at the controller, then in bootstrap-enabled layout.haml I define:

  ...
  %body
    .navbar.navbar-fixed-top
      .navbar-inner
        .container
          %a.btn.btn-navbar{"data-target" => ".nav-collapse", "data-toggle" => "collapse"}
            %span.icon-bar
            %span.icon-bar
            %span.icon-bar
          %a.brand{:href => "/"} AwesomeApp
          .nav-collapse
            %ul.nav
              %li{:class => @@menu == 'home' && :active}
                %a{:href => "/"} Home
              %li{:class => @@menu == 'about' && :active}
                %a{:href => "/about"} About
              %li{:class => @@menu == 'contact' && :active}
                %a{:href => "/contact"} Contact

when I set @@menu to 'about' it will render:

  <body>
    <div class='navbar navbar-fixed-top'>
      <div class='navbar-inner'>
        <div class='container'>
          <a class='btn btn-navbar' data-target='.nav-collapse' data-toggle='collapse'>
            <span class='icon-bar'></span>
            <span class='icon-bar'></span>
            <span class='icon-bar'></span>
          </a>
          <a class='brand' href='/'>AwesomeApp</a>
          <div class='nav-collapse'>
            <ul class='nav'>
              <li>
                <a href='/'>Home</a>
              </li>
              <li class='active'>
                <a href='/about'>About</a>
              </li>
              <li>
                <a href='/contact'>Contact</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
Related