Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap grid system formatting photos in Rails

i'm in rails with bootstrap.

i have a product site with many products. i need to display my products in a grid format for the "store front". each product has a photo and some info.

i saw this post and this post but they are not what i'm looking for.

i am trying to iterate over each product using product.each while attempting to use bootstrap's grid system.

i will need to add additional products as time goes on and therefore need each product to flow from one row to the next. i have not used any additional css styling outside of bootstrap.

as of now, i appears that each products is dropping to next row and that each product is inside it's own column, but any attempt i make to resize the image or the div or col that each product is inside, everything becomes misaligned.

here is my html.erb file:

<div class="row">
 <% @products.each do |product| %>
  <div class="col-md-3">
   <div id="storeimages">
    <%= image_tag(product.image_url, class: "img-responsive") %>
    <h3><%= product.title %></h3>
    <div><%= sanitize(product.description) %></div>
    <div><%= number_to_currency(product.price) %></div> 
    <%= button_to 'Add to Cart', line_items_path(product_id: product), 
         class: 'btn btn-info btn-sm', remote: true %>
   </div>
  </div>
 <% end %>
</div>
like image 789
kacy hulme Avatar asked Dec 12 '22 06:12

kacy hulme


1 Answers

Assuming you want rows of 4 columns, you could do something like this:

<% @products.in_groups_of(4, false).each do |group| %>
  <div class='row'>
    <% group.each do |product| %>
      <div class='col-md-3'>
        <%= image_tag(product.image_url, class: "img-responsive") %>
        <h3><%= product.title %></h3>
        <div><%= sanitize(product.description) %></div>
        <div><%= number_to_currency(product.price) %></div> 
        <%= button_to 'Add to Cart', line_items_path(product_id: product), class: 'btn btn-info btn-sm', remote: true %>
      </div>
    <% end %>
  </div>
<% end %>

This splits your data set up into groups of 4 items, then outputs a row div for each group. Then within each row, it outputs each member of the group in its own column div.

The false passed in to in_groups_of ensures that you don't try to output a column for a row where there are less than 4 items. This would happen on your last row if your total number of products was not exactly divisible by 4 since by default the function will pad out the array with nil.

Thanks to @vermin for the fill_with tip!

like image 195
Jon Avatar answered Dec 21 '22 12:12

Jon