Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails/Haml: adding a parentclass every n iteration

I have a photo gallery that is organised like this:

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

Let's 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 do so that a .container gets added every 3 %li ?

like image 861
Alex Avatar asked Feb 20 '23 04:02

Alex


2 Answers

I guess method Array#in_groups_of is what you 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 this method you can also define replacement for missing images

%w(1 2 3 4).in_groups_of(3, '_') {|group| p group}
# => ["1", "2", "3"]
# => ["4", "_", "_"]
like image 158
hs- Avatar answered Feb 28 '23 12:02

hs-


I would try something like this:

- @images.each_slice(3) do |images|
  .container
    - images.each do |image|
      %li
        %a{src: image.src}
like image 28
Luke Avatar answered Feb 28 '23 10:02

Luke