HOW TO: Easily output alternating item styles via metaprogra


#1

I always need to apply alternating item styles when outputting a
collection,
here’s what I’ve been using recently.

In the app helper I define this method:

def alternate(items,alt=false
items.map{|i| i.class}.each { |k| k.class_eval {attr_accessor :alt}}
items.each { |i| i.alt, alt = alt, !alt }
end

When I call the partial I wrap the collection with this method:

<%= render :partial => ‘story’, :collection => alternate(@stories) %>

Now in the partial each object in the collection has the alt attribute
available:

  • ">

    Obviously I’m making the assumption that the objects don’t already
    have/use
    an alt attribute. Anyone solving this similarly?

    • Nathan

  • #2

    On 7/3/07, blinking bear removed_email_address@domain.invalid wrote:

    Obviously I’m making the assumption that the objects don’t already
    have/use an alt attribute. Anyone solving this similarly?

    • Nathan

    To be honest I’m not really following your code.

    items.each { |i| i.alt, alt = alt, !alt } What is this doing?

    I must be missing something because it seems that every call to alt
    should
    return false from the setup in the alternate method.

    My mind went to the cycle method, but I’m not sure if that fits or not
    since
    I don’t follow your code.

    Anyway the docs are
    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000628

    Cheers
    Daniel


    #3

    <%= render :partial => ‘story’, :collection => alternate(@stories) %>

  • ">
  • seems kinda ferocious to me… you could use the partial counter to
    count even uneven objects, and then style them accordingly:

    ===========some.rhtml===============

    <%= render :partial => ‘story’, :collection => @stories %>

    =======_story.rhtml=================

  • works for ya…?


  • #4

    Shai,
    haha - ferocious? you’re right

    your solution worked (just needed another ?):

  • thanks,
    nathan


  • #5

    your solution worked (just needed another ?):

  • oh yea, thanks…glad it helps :slight_smile:


    #6

    If you just want to use another style for every odd row, I’m using
    something
    like this:

    <% @page.items.each do |item| %>

    "> ... <% end %>

    API:
    http://api.rubyonrails.org/classes/ActionView/Helpers/TextHelper.html#M000628

    Regards,
    Timo