Search code examples
cssruby-on-railsrubycyclehtml-table

Alternate column (<td>) classes and maybe even column content in rails?


In rails I know you can do

<tr class="<%= cycle("even", "odd") %>">

to cycle the class for a given row.

But in cases like this

<% @products.each do |p| %>
<tr class="headers">
    <td><%= p.name %></td>
    <td><%= p.idnum %></td>
    ...
</tr>
<% end %>

how might I automatically alternate the column class?

Is there some way I could something like this? (inventing some fanciful method names ('.column_names') for sake of illustration)

<% @products.each do |p| %>
    <tr class="headers">
        <% products.column_names.each do |c| %>
            <td class="<%= cycle("even", "odd") %>"><%= c %></td>
        <% end %>
    </tr>
<% end %>

EDIT: (case in point)

<table>
  <tr class="headers">
    <td class="even">&nbsp;</td>
    <td class="odd">Name</td>
    <td class="even">Followers</td>
    <td class="odd">Date Joined</td>
    <td class="even">Slogan</td>
    <td class="odd">Location(s)</td>
    <td class="even">Segments(s)</td>
    <td class="odd">Website</td>
  </tr>
  <tr class="body">
    <td class="even"><img src="<%= company.thumbnail_logo %>"></td>
    <td class="odd"><%= company.company_name %></td>
    <td class="even"><%= company.followers %></td>
    <td class="odd">...</td>
    ...
  </tr>
</table>

This is what I'm in the middle of writing currently, and as you can see it's fairly verbose. I'm looking to cut down on that.


Solution

  • Is this just for styling purposes? You can use CSS3 to do this without having to assign classes.

    tr:nth-of-type(even){ your_css_here }
    

    or

    td:nth-of-type(even){ your_css_here }
    

    Replace even with odd if that's what you want

    Also, wouldn't you use <th> for headers?