Rails 每个循环插入标签每 6 个项目? [英] Rails each loop insert tag every 6 items?
问题描述
我需要在视图中循环遍历 X 个图像对象,并且希望每 6 个对象左右创建一个新 div(对于画廊).
我看过循环,但它似乎改变了所有其他记录.有人知道每 6 次将代码插入视图的方法吗?
我可能可以用嵌套循环来做到这一点,但我对这个有点难.
您可以将 Enumerable#each_slice
与 #each
结合使用以避免内联计算.each_slice
将数组分成 n 个块,在本例中为 6.
<% @images.each_slice(6) 做 |slice|-%><div class="gallery"><% slice.each do |image|-%><%= image_tag(image.url, :alt => image.alt) %><%结束-%>
<%结束-%>
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.
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 -%>
这篇关于Rails 每个循环插入标签每 6 个项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!