【问题标题】:Render n objects at a time, inserting code then repeating for the next n objects - Rails一次渲染 n 个对象,插入代码然后重复下一个 n 个对象 - Rails
【发布时间】:2012-07-30 18:19:24
【问题描述】:

新手,非常感谢一些帮助以 3 组渲染对象。

我目前显示一个带有渲染的对象列表:

<%= render @gifts %>

每个对象都有一些从部分 _gift.html.erb 呈现的特征

这一切都很好。但是,如何遍历所有 @gifts 对象,每 3 个对象用一个 div 包装?期望的结果是这样的:

<div class="row-fluid>
# The first 3 objects from @gifts
</div>

<div class="row-fluid>
# The next 3 objects from @gifts
</div>

【问题讨论】:

    标签: ruby-on-rails ruby object loops render


    【解决方案1】:
    <% @gifts.each_slice(3) do |slice| %>
      <div class="row-fluid>
        # slice now is a 3 element array, iterate over it and render as you see fit
      </div>
    <% end %>
    

    我更像是一个 HAML 人,但这应该可行。

    【讨论】:

      【解决方案2】:

      each_slice 是您正在寻找的。这里有更详细的介绍:

      https://stackoverflow.com/a/2852103/9465

      【讨论】:

        【解决方案3】:

        还可以考虑 in_groups_of(Rails 猴子补丁到数组):

        http://apidock.com/rails/Array/in_groups_of

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-02-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-07-20
          • 1970-01-01
          • 1970-01-01
          • 2012-06-16
          相关资源
          最近更新 更多