Test Test
Test Test

Reputation: 2889

How to print an HTML table using Ruby?

This is my code:

<table class="video_table">
  <% count = 0 %>
  <tr>
  <% @f_videos.each do |f_video| %>
     <td><%= f_video.name %></td>
     <td><%= f_video.date_added %></td>
     <td><%= f_video.views %></td>
     <% count +=1 %>
     <% if count == 4 %>
         </tr>
     <% end %>
  <% end %>
</table>

at each 4 videos placed I want the table to switch row. So I implemented a counter. But it is not working. Any ideas?

Upvotes: 1

Views: 487

Answers (2)

Marek Př&#237;hoda
Marek Př&#237;hoda

Reputation: 11198

Another solution:

<table class="video_table">
<% @f_videos.in_groups_of(4) do |group| %>
  <tr>
    <% group.each do |f_video| %>
      <td><%= f_video.name %></td>
      <td><%= f_video.date_added %></td>
      <td><%= f_video.views %></td>
    <% end %>
  </tr>
<% end %>
</table>

in_groups_of has the added value/advantage that, when needed, it allows for padding any remaining slots with eg '&nbsp;', which can be very useful. See the docs.

Upvotes: 1

maček
maček

Reputation: 77778

Your count will only be set to 4 once.

Instead of if count == 4 use if count % 4 == 0

This will repeat the </tr> for each multiple of 4


Alternatively, you could skip using the count variable and use each_with_index to get the same result

<table class="video_table">
<% @f_videos.each_with_index do |f_video, i| %>
  <tr>
    <td><%= f_video.name %></td>
    <td><%= f_video.date_added %></td>
    <td><%= f_video.views %></td>
    <% if (i+1) % 4 == 0 %>
      </tr>
    <% end %>
<% end %>
</table>

Even better! each_slice

<table class="video_table">
<% @f_videos.each_slice(4).to_a do |slice| %>
  <tr>
    <% slice.each do |f_video| %>
      <td><%= f_video.name %></td>
      <td><%= f_video.date_added %></td>
      <td><%= f_video.views %></td>
    <% end %>
  </tr>
<% end %>
</table>

Upvotes: 2

Related Questions