Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
598 views
in Technique[技术] by (71.8m points)

ruby - Rails each loop insert tag every 6 items?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...