Rails / Haml: adding a parent class to each iteration

I have a photo gallery, which is organized as follows:

.container %li %a{src: image.src} %li %a{src: image.src} %li %a{src: image.src} .container %li %a{src: image.src} %li %a{src: image.src} %li %a{src: image.src} 

Each container should have a maximum of 3 %li .

Say I have @images where @images.count => 4 .

 .container - for image in @images do %li %a{src: image.src} 

This code will break the page because in this case .container has 4 %li .

How can I make .container added every 3 %li ?

+4
source share
3 answers

I assume that the Array # in_groups_of method is what you are looking for.

 - @images.in_groups_of(3, false).each do |images| .container - images.each do |image| %li %a{src: image.src} 

By the way, using this method, you can also determine the replacement of missing images

 %w(1 2 3 4).in_groups_of(3, '_') {|group| p group} # => ["1", "2", "3"] # => ["4", "_", "_"] 
+7
source

I would try something like this:

 - @images.each_slice(3) do |images| .container - images.each do |image| %li %a{src: image.src} 
+1
source

Using the ruby ​​each_slice method on @images http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-each_slice

 - @images.each_slice(3) do |i| .... 
0
source

Source: https://habr.com/ru/post/1433648/


All Articles