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>
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With