开发者

Rails creating a thumbnail gallery in my view

I currently have an Array that contains some URL's to 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 is 3 columns across in my view. The HTML out put would 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 gets me a one column table

<table>

<tr>

<% @images.each do | image | %>开发者_运维百科;

<td><%= image_tag(image)%></td><br>

<% end %>

</tr>

</table>

In the future I might want it to be 6 columns instead of 3 columns. I'm looking for a way to do this in a clean and flexible way.

I was looking at 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 Range class step method can solve the problem but the example it provides is interesting.

Any thoughts, I'm still learning and maybe I'm over thinking this?


use each_slice()

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


Untested. You need to use each_with_index and the modulus % operator.

<% @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 %>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜