Rails creating a thumbnail gallery in my view

I currently have an array containing the URL for the images.

@images = [ "http://site/images/01.jpg", "http://site/images/02.jpg" ]

Total 18 images

I would like to take this array and create a thumbnail gallery where the gallery has 3 columns in my view . HTML out put will be

<table>
<tr>
<td><img src="http://site/images/01.jpg"></td>
<td><img src="http://site/images/02.jpg"></td>
<td><img src="http://site/images/03.jpg"></td>
</tr>
<tr>
<td><img src="http://site/images/04.jpg"></td>
<td><img src="http://site/images/05.jpg"></td>
<td><img src="http://site/images/06.jpg"></td>
</tr>
</table>

My current implementation returns me one column table

<table>
<tr>
<% @images.each do | image | %>
<td><%= image_tag(image)%></td><br>
<% end %>
</tr>
</table>

In the future, I may need 6 columns instead of 3 columns. I am looking for a way to do this in a clean and flexible way.

I watched the Ruby documentation and I saw this Class Range (rng.step method) http://www.ruby-doc.org/core/classes/Range.html

Not sure if this class method can solve the problem, but an interesting example.

, , , , .

+3
2

each_slice()

<table>
  <% @images.each_slice(3) do |images| %>
    <tr>
      <% images.each do |image| %>
        <td><%= image_tag(image) %></td>
      <% end %>
    </tr>
  <% end %>
</table>
+7

. each_with_index %.

<% @images.each_with_index | image, index | %>
   <% unless index % column_count == 0 %>
         <td><%= image_tag(image)%></td>
   <% else %>
         <td><%= image_tag(image) %></td>
      </tr>
      <tr>
   <% end %>
<% end %>
+1

Source: https://habr.com/ru/post/1784996/


All Articles