Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Classify() For Alternating Rows, Columns, Etc.

DZone's Guide to

Classify() For Alternating Rows, Columns, Etc.

·
Free Resource
I often want different rows in a table to alternate in color, and I do this by assigning each row a class name and styling it with CSS.  This is a simple helper method designed to return a class name based on the given row count.

It is also convenient for me to assign a class to table cells based on the type of content they hold.  For example, if I have a cell with a float value in it, I want to display it with a monospace font, whereas if I have a cell with a string in it, I want to display it in a serif font.

# Determines the CSS class based on either the count given
# (returns 'even' or 'odd' as the CSS class name) or the class
# given (returns the string version of the class, lowercased,
# as the CSS class name)
def classify( count_or_class, include_class_text = true )
  if count_or_class.class == Fixnum
    value = ( count_or_class % 2 == 0 ? 'even' : 'odd' )
  else
    value = count_or_class.to_s.downcase
  end

  if include_class_text
    'class="' << value << '"'
  else
    value
  end
end

Example usage with alternating 'even'/'odd' row class names:

  
   
<% count = 0 %>
<% @collection.each do |value| %>
  
   
     >
    
     
  <% count += 1 %>
<% end %>

   
<%=h value %>
Example usage with data type class names: <% @columns.each do |column| %> <% data = row.send( column.name ) %> > <%=h data %> <% end %>
Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}