html.erb - 如何用空 div 填充最后一行

标签 html ruby-on-rails ruby

我的 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/

相关文章:

android - Android 会在即将发布的版本中支持 WebSockets 吗?

javascript - 当用户滚动到特定的 div 时运行 javascript 函数

html - 使用 z-index 使一个嵌套元素位于其他元素之前?

html - 对齐图片,使其不在导航列表下换行。

ruby-on-rails - 如何在 resque rails 中连接单独的 redis 实例

ruby-on-rails - 打开 PDF 文件并在其中搜索名称

ruby - 将字符串拆分为指定大小的 block 而不打断单词

sql - 在 Rails Console for PostgreSQL 的表中显示数据

mysql - 为了 Heroku,从 MySQL 切换到 PostgreSQL for Ruby on Rails

jquery - Rails 远程表单回调 ajax :loading does not fire, 其他人做