Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

haml conditional if/else indentation

I have a situation where I want to add a class to a div tag only when the count is greater than 0

Example:

- @color.shades.each_with_index do |shade, index|
    - if index == 0
        #shades
    - else
        #shades.horizontalLine.second
     %h3 something
     %dl 
         %dt some
         %dd some1

In this example I want everything starting from %h3 to come under either #shades or #shades.horizontalLine.second depending on however those if and else statements evaluate.

work around is:

- @color.shades.each_with_index do |shade, index|
    - if index == 0
        #shades
          %h3 something
            %dl 
              %dt some
              %dd some1
    - else
        #shades.horizontalLine.second
          %h3 something
            %dl 
              %dt some
              %dd some1

but here I have to repeat code

I'm stumped at how to do this in rails without repeating the code starting from %h3 for both the divs.

like image 885
Mike Avatar asked Sep 01 '11 01:09

Mike


1 Answers

You can set the class to a variable holding the class names based on the index to DRY it up:

- @color.shades.each_with_index do |shade, index|
  - shade_classes = index == 0 ? '' : 'horizontalLine second'
    #shades{ :class => shade_classes }
      %h3 something
        %dl 
          %dt some
          %dd some1
like image 182
Winfield Avatar answered Oct 19 '22 01:10

Winfield