I am trying to make a responsive image grid (here is an example from w3schools: Responsive Image Grid ). From the example, they have the following html
:
<div class="row">
<div class="column">
<img src="/w3images/wedding.jpg" style="width:100%">
<img src="/w3images/rocks.jpg" style="width:100%">
<img src="/w3images/falls2.jpg" style="width:100%">
<img src="/w3images/paris.jpg" style="width:100%">
...
</div>
<div class="column">
<img src="/w3images/underwater.jpg" style="width:100%">
<img src="/w3images/ocean.jpg" style="width:100%">
<img src="/w3images/wedding.jpg" style="width:100%">
<img src="/w3images/mountainskies.jpg" style="width:100%">
...
</div>
<div class="column">
<img src="/w3images/wedding.jpg" style="width:100%">
<img src="/w3images/rocks.jpg" style="width:100%">
<img src="/w3images/falls2.jpg" style="width:100%">
<img src="/w3images/paris.jpg" style="width:100%">
...
</div>
<div class="column">
<img src="/w3images/underwater.jpg" style="width:100%">
<img src="/w3images/ocean.jpg" style="width:100%">
<img src="/w3images/wedding.jpg" style="width:100%">
<img src="/w3images/mountainskies.jpg" style="width:100%">
...
</div>
</div>
However, they are using static content. I want to make the content dynamic. I've done some research and found the following solution: Return every nth row from database using ActiveRecord in rails . Not sure if this is the right way, but my goal is to put every n
element in each column
without specifying the limit.
Currently, I have the following code in my controller:
def index
@photos = Photos.is_active.all
end
Index view:
= render partial: "photos", collection: @photos
Is there any right way to implement the solution from w3school and make a dynamic content with Ruby on Rails loop?
in_groups_of
does exactly what you're looking for.
Splits or iterates over the array in groups of size number
, padding any remaining slots with fill_with
unless it is false
.
%w(1 2 3 4 5 6 7 8 9 10).in_groups_of(3) {|group| p group}
["1", "2", "3"]
["4", "5", "6"]
["7", "8", "9"]
["10", nil, nil]
%w(1 2 3 4 5).in_groups_of(2, ' ') {|group| p group}
["1", "2"]
["3", "4"]
["5", " "]
%w(1 2 3 4 5).in_groups_of(2, false) {|group| p group}
["1", "2"]
["3", "4"]
["5"]
Editing the original question. I would propose:
Each_slice: https://apidock.com/ruby/Enumerable/each_slice
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.