【问题标题】:How to automatically generate rows in Html/Rails?如何在 Html/Rails 中自动生成行?
【发布时间】:2018-07-19 12:08:09
【问题描述】:

所以我有一个产品列表。 例如:

<table>    
  <tr>
    <% products.ascend_by_name.each do |product| %>
      <td id="product_<%= product.id %>">
        #-CONTENT HERE-#
      </td>
    <% end %>
  </tr>
</table>

我想让它每 3 个产品生成一行。 因此:

<table>    
  <tr>
    <td id="product_<%= product.id %>">
      #-CONTENT HERE-#
    </td>
    <td id="product_<%= product.id %>">
      #-CONTENT HERE-#
    </td>
    <td id="product_<%= product.id %>">
      #-CONTENT HERE-#
    </td>
  </tr>
  <tr>
    <td id="product_<%= product.id %>">
      #-CONTENT HERE-#
    </td>
    <td id="product_<%= product.id %>">
      #-CONTENT HERE-#
    </td>
    <td id="product_<%= product.id %>">
      #-CONTENT HERE-#
    </td>
  </tr>
</table>

有什么方法可以实现吗?

【问题讨论】:

  • 对不起。我回答得很快(而且错了),所以我删除了答案。
  • 一定是桌子?也许您可以使用 flex 容器实现更好的效果(并且响应速度更快,根据屏幕大小改变列数)。
  • @Pablo 不,它不必是一张桌子,flex 可以工作,但是我如何进入行?事实上,我这样做的唯一原因是在每一行之间有一个边界。但我不能单独添加边框,因为产品的高度不同

标签: html ruby-on-rails html-table rows


【解决方案1】:

为此使用in_groups_of (https://apidock.com/rails/Array/in_groups_of)。示例:

<table>    
  <% products.ascend_by_name.in_groups_of(3, false) do |product_group| %>
    <tr>
      <% product_group.each do |product| %>
        <td id="product_<%= product.id %>">
          #-CONTENT HERE-#
        </td>
      <% end %>
    </tr>
  <% end %>
</table>

【讨论】:

  • 谢谢!这正是我想要的!
【解决方案2】:

我认为显示项目列表(如果您想每行显示多个项目)的更好方法是使用弹性容器。

您可以在这支笔中查看它的工作原理:https://codepen.io/ppintaluba/pen/YeNjzp

html.erb 文件

<div class="flex-container">

  <% products.ascend_by_name.each do |product| %>

    <div class="flex-item" id="product_<%= product.id %>">
      #-CONTENT HERE-#
    </div>
  <% end %>

</div>

scss 文件

// Change values as necessary
.flex-container {
  min-width: 745px;
  margin: 4em auto;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: flex-start;
}

// Change values as necessary
.flex-item {
  text-align: center;
  min-width: 240px;
  max-width: 100%;
  min-height: 100px;
  margin: 0 10px 20px 0;
  padding: 10px 0px 10px 0px;  
  border-style: solid;
  border-width: 1px;
  border-color: #000000;
  background: #247696;

 // Slow animations
  -webkit-transition: all .25s;
     -moz-transition: all .25s;
      -ms-transition: all .25s;
       -o-transition: all .25s;
          transition: all .25s;
}

// Some animations when hovering each item (increase size)
.flex-item:hover {
  -webkit-transform: scale(1.05);
     -moz-transform: scale(1.05);
      -ms-transform: scale(1.05);
       -o-transform: scale(1.05);
          transform: scale(1.05);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-06
    • 2011-09-13
    • 2019-02-05
    相关资源
    最近更新 更多