【问题标题】:Putting first X images in a different container from last Y images将前 X 图像放在与最后 Y 图像不同的容器中
【发布时间】:2014-09-03 23:45:33
【问题描述】:

这看起来很简单,但想不通...我有一个包含 13 个图像的列表 (@images),我在视图中这样称呼它们:

<div class="col-xs-12" style="margin-left: 50px;">
<% @images.each do |image, key| %>
    <div class="col-xs-1" id="<%= "#{image}" %>"> 
        <%= image_tag("Portrait thumbnails/#{image}.jpg", class: "img-responsive thumbnail", alt: "#{image}", title: "#{image}") %>
        <h6><%= "#{image}" %></h6>
    </div>
<% end %>
</br>

问题在于,因为 13 张图片不能横向放置,我想将它们分成两行,每行 6 张和 7 张图片。我怎么做?我试过了:

  • each_with_index 但是由于索引也是循环的,所以我不能在索引部分之外放置一个容器
  • @images.first(6) 作为临时解决方案,但后来我意识到,由于这会将哈希扁平化为数组,因此不适用于 @images.last(7)

更理想,我想要一个可扩展的解决方案,这意味着程序会自动计算图像的数量,并将每个 col-xs-12 行分成 6 个。我知道我可以通过为每组 6 个图像创建一个不同的实例变量来手动执行此操作,但这太手动了,必须有一种我只是没有想到的编程方式。

【问题讨论】:

    标签: html ruby-on-rails ruby-on-rails-4 twitter-bootstrap-3 each


    【解决方案1】:

    您可以为此使用Enumerable#each_slice

    <% @images.each_slice(6) do |images| %>  # Split into slices of 6
      <div class="col-xs-12">
        <% images.each do |image| %> # Loop through each item in the slice 
          <div class="col-xs-1">
            .. 
          </div>
        <% end %>
      </div>
    <% end %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-16
      • 2012-10-25
      • 1970-01-01
      • 2023-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多