views:

268

answers:

2

Hello Stack Anon,

I have X number of image objects that I need to loop through in a view and want to create a new div every 6 objects or so (for a gallery).

I have looked at cycle but it seems to change every other record. Does anyone know of a way to insert code into a view every 6 times?

I could probably do it with nested loops but I am kinda stumped on this one.

Thanks!

+2  A: 

This is a Ruby question. You can meld this into whatever your view is trying to do.

@list.each_with_index do |item, idx|
  if((idx + 1) % 6 == 0)
    # Poop out the div
  end
  # Do whatever needs to be done on each iteration here.
end
jdl
Perfect. Your right, it is Ruby really.Thank you. :)
Dustin M.
+6  A: 

You can use Enumerable#each_slice in conjunction with #each to avoid inline calculations. each_slice breaks the array into chunks of n, in this case 6.

<% @images.each_slice(6) do |slice| -%>
  <div class="gallery">
    <% slice.each do |image| -%>
      <%= image_tag(image.url, :alt => image.alt) %>
    <% end -%>
  </div>
<% end -%>
thorncp
That seems like a more conventional way to do it.. I'll give a a try.
Dustin M.
Thanks Thorn, I prefer this method to keep my views clean. Thanks!
Dustin M.