jdstrong95
jdstrong95

Reputation: 63

How to automatically generate rows in Html/Rails?

So I have a list of products. For Example:

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

I would like to make it so that a row is generated every 3 products. As such:

<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>

Is there any way of achieving this?

Upvotes: 0

Views: 131

Answers (2)

Pablo
Pablo

Reputation: 3005

I think a better approach to show a list of items (if you want to show more than one per row) is to use flex containers.

You can check how it works in this pen: https://codepen.io/ppintaluba/pen/YeNjzp

html.erb file

<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 file

// 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);
}

Upvotes: 0

Sean Huber
Sean Huber

Reputation: 3985

Use in_groups_of for this (https://apidock.com/rails/Array/in_groups_of). Example:

<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>

Upvotes: 2

Related Questions