Table with dynamic content

I want to create a table displaying image thumbnails, 3 per row.
Can I use an if loop to create the <tr> tags?

or is this better acheived with css?

I want to create a table displaying image thumbnails, 3 per row.
Can I use an if loop to create the <tr> tags?

"if" doesn't produce a loop - it's just a conditional check.

Assuming your images are stored in an array, you can use any of a
number of methods to loop them.

* you could do .each_with_index and then start a new row on mod-3 of the index
* you could use .each_slice(3) and iterate the returned array of three
* you could (if you like it clunky) just use .each maintain your own
counter and do your next row operations when it gets to a multiple of
3

http://www.ruby-doc.org/core/classes/Enumerable.html

or is this better acheived with css?

Probably (for all sorts of "tables are for tabular data" reasons). But
the problem of working out how to tell the element it's a new row will
be very similar to using a table (unless you rely on overflow wrapping
in a fixed-size container).

* you could (if you like it clunky) just use .each maintain your own
counter and do your next row operations when it gets to a multiple of
3

I think that's what I was trying to do, though I didn't know how to get
a new table row
was I on the right track?

<table>
<% @photos.each do |photo| %>
<% count = 0 %>
<% while count <= 3 %>
<tr>
  <td><%= link_to image_tag(photo.image.url(:thumb)), photo %></td>
  <% count += 1 %>
<tr/>

<% end %>
...

I did try to hint that that was a poor option with all the Ruby
goodness available to you! :slight_smile:

Try:

<table>
  <% @photos.each_slice(3) do |photos_row| %>
    <tr>
      <% photos_row.each do |photo| %>
        <td><%= link_to image_tag(photo.image.url(:thumb)), photo %></td>
      <% end %>
      <% # could do with some check here to pad out row with blank
cells if any cell has less than three - to produce valid HTML
(wouldn't need to worry about this with CSS placement :slight_smile: %>
      <tr/>
  <% end %>
</table>

You could also pass the "<td>" drawing bit off to its own partial and
pass it the photos-row collection; but that might be one step too far
for you right now.

Not sure that you would want to do this but you can

a = (1…20).to_a

until a.empty?

x = a.slice!(0,3)

puts x.inspect

end

Gives

[1, 2, 3]

[4, 5, 6]

[7, 8, 9]

[10, 11, 12]

[13, 14, 15]

[16, 17, 18]

[19, 20]

so you could have

<% until @photos.empty? -%>

<% x = @photos.slice!(0,3) -%>

<% x.each do |y| -%>

<% end -%>

<% end -%>

<%= y %>

<% @photos.in_groups_of(3, false) do |group| %>
  <tr>
  <% group.each do |photo| %>
    <td><%= photo.filename_or_whatever %></td>
  <% end %>
  </tr>
<% end %>

or something relatively close to that