Instead of looping twice, you could create a method that extracts the
color choosing logic that is currently in your controller and simply
call this method from the view.  This method could be in a Helper or
in Person model.  I tend to avoid putting view related methods in the
Model.

Your rhtml becomes:
<% for person in @people -%>
  ...
  <span class="color<%= color_for(person) -%>person.name</span>
  ...
<% end -%>

Making your haml:
- @people.each |person|
  %span{:class => color_for(person)} person.name


In person_helper.rb:
def color_for(person)
  color_index = #insert color choosing logic extracted from controller
@color hash creation.
  # this *could* be:
  # color_index = person.color_index

  return "color#{color_index}"
end

Some would prefer we name the method 'color_for_person'.  Since this
resides in the person_helper, I'm fine with color_for.

You could also have your method return the whole hash (see
http://haml.hamptoncatlin.com/release-notes).  Note: this hash could
include multiple attributes (please rename the method when doing
this).

Making your haml:
- @people.each |person|
  %span{color_class(person)} person.name

In person_helper.rb:
def color_class(person)
  {:class => color_for(person)}
end

--Matt


On Jul 21, 8:46 am, Dave Roberts <[EMAIL PROTECTED]> wrote:
> I should have specified:
>
> Can this be done in a more efficient way at all.  Right now I loop
> through all the people in the controller a first time to assign the
> colors, and again in the view to display them.  I'd like to keep it
> down to one loop if possible, and keep logic out of that loop if it is
> in the view (to not violate MVC).
>
> On Jul 21, 8:43 am, Dave Roberts <[EMAIL PROTECTED]> wrote:
>
> > I have an application where I list expenses shared by people.
> > After each expense, I list the person's names associated with the
> > charge.
> > I would like each person's name to be colored differently, but each
> > occurance of the same name to be colored the same color.
> > To achieve this, I would create a hash called @color in the
> > controller, where each person's id maps to a different number
> > Using RHTML I would do this:
>
> > <% for person in @people -%>
> >   ...
> >   <span class="color<%= @color[person.id] -%>person.name</span>
> >   ...
> > <% end -%>
>
> > this would alter the class to be color2, color11, color6 or whatever,
> > which would represent a different color in my CSS.
>
> > I have two questions:
>
> > 1) Can this be done a more efficient way using Haml and Sass?
> > 2) How can it be done?


--~--~---------~--~----~------------~-------~--~----~
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