我的 Rails 应用程序中有一个 View ,它是一个图片库。 View 如下所示:
view.html.erb
<div class="photo-row">
<% @item.item_images.each_with_index do |image, index| %>
<% if (index % 3 == 0) && (index != 0) %>
</div><div class="photo-row">
<% end %>
<div class="photo-wrapper">
<a class="fancybox" rel="group" href="<%= image.picture.large.url %>"><img class="pending-photo" src="<%= image.picture.small.url %>" alt="" /></a>
</div>
<% end %>
</div>
如您所见,该行将填满三个图像,然后创建一个新行。为了对齐,我需要在最后一个非完整行中填充 3 个 photo-wrapper
div。例如,如果 @item
有 7 个 item_images
,我需要有 3 行。前两个是完整的,最后一个应该有 1 个带有图像和 2 个空包装。
我怎样才能做到这一点?
最佳答案
我会使用 in_groups_of
helper 。它将您的数组分成给定大小的组。缺少的元素用 nil
填充默认情况下。
像这样的东西应该可以工作:
<% @item.item_images.in_groups_of(3) do |images| %>
<div class="photo-row">
<% images.each do |image| %>
<div class="photo-wrapper">
<% if image %>
<a class="fancybox" rel="group" href="<%= image.picture.large.url %>"><img class="pending-photo" src="<%= image.picture.small.url %>" alt="" /></a>
<% end %>
</div>
<% end %>
</div>
<% end %>
您还可以使用 link_to
和 image_tag
助手而不是 <a>
和 <img>
标签。可能包裹在自定义助手中:
# app/helpers/application_helper.rb
def fancybox(image)
link_to image.picture.large.url, class: 'fancybox', rel: 'group') do
image_tag(image.picture.small.url, alt: '', class: 'pending-photo')
end
end
在你看来:
<% @item.item_images.in_groups_of(3) do |images| %>
<div class="photo-row">
<% images.each do |image| %>
<div class="photo-wrapper">
<%= fancybox(image) if image %>
</div>
<% end %>
</div>
<% end %>
[请注意,我还没有测试这段代码,它可能包含错误]
关于html.erb - 如何用空 div 填充最后一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36891418/