First of all, I'd recommend using the #each_with_index method rather than
manually maintaining a counter:
http://www.ruby-doc.org/core/classes/Enumerable.html#M003137

To address your specific issue, though, remember that Haml attributes are
just Ruby code. So rather than having three separate definitions of
%div.grid_2.actor, you can just do

    .grid_2.actor{:class => actor_class(counter)}

Where you'd define the actor_class helper as so:

    def actor_class(counter)
      case counter % 4
      when 1; "alpha"
      when 0; "omega"
      else; nil
      end
    end

Haml will merge the two class definitions together, so you'll get the result
you want.

On Mon, May 17, 2010 at 4:24 PM, bongoman <[email protected]> wrote:

> Hi there
>
> I'm using haml in a Sinatra app that is using the 960gs framework.
>
> I'm laying out a grid of thumbnail images and need to append an alpha
> class to the first in a row of 4, and an omega class to the last in
> the row, hence the counter.modulo.
>
> However I'm having trouble balancing conditional output with HAML
> indentation and am struggling to DRY this up:
>
> ===============
> %div#picgrid.grid_8
>  -counter = 1
>  [email protected] do |a|
>    -if counter.modulo(4) == 1
>      %div.grid_2.alpha.actor
>        %a{:href => "/#{params[:type]}/detail/#{a["id"]}", :class =>
> "detail"}
>          %img{:src => "#{a["photos"][0]}", :class => "grid_pic"}
>    -elsif counter.modulo(4) == 0
>      %div.grid_2.actor.omega
>        %a{:href => "/#{params[:type]}/detail/#{a["id"]}", :class =>
> "detail"}
>          %img{:src => "#{a["photos"][0]}", :class => "grid_pic"}
>      %div.clear
>    -else
>      %div.grid_2.actor
>        %a{:href => "/#{params[:type]}/detail/#{a["id"]}", :class =>
> "detail"}
>          %img{:src => "#{a["photos"][0]}", :class => "grid_pic"}
>    -counter += 1
>  %p Non-conditional content goes here.
> =================
>
> This works but I don't want to keep repeating the img wrapped in an a
> tag for each of the conditions - yet if I try and DRY this up I get
> all hooked up with the interrelationship between the indentation of my
> html tags and the indentation requirements of the conditional ruby.
>
> I only need to conditionally output the div.grid_2 and not the a and
> nested img.
>
> Any clues appreciated.
>
> --
> You received this message because you are subscribed to the Google Groups
> "Haml" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected] <haml%[email protected]>.
> For more options, visit this group at
> http://groups.google.com/group/haml?hl=en.
>
>

-- 
You received this message because you are subscribed to the Google Groups 
"Haml" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to [email protected].
For more options, visit this group at http://groups.google.com/group/haml?hl=en.

Reply via email to