div#container
each account in accounts
button #{account.stuff}
I want to group the buttons inside a div. Every div has to have 10 (or less if there’s some left over).
I would prefer to not use any JS. Altough, if necessary, a bit of CSS is fine (I would prefer just Pug)
I tried using a grid, but dont want to use CSS.
I tried using ifs and mods, but that just creates an empty without actually any buttons.
2
Answers
You can achieve this grouping of buttons inside a div by using Pug’s
each
loop andslice
method to split theaccounts
array into chunks of 10 or less. Then, you can wrap each chunk of buttons inside adiv
element using Pug’s string interpolation and iteration capabilities.Here’s an example code snippet that demonstrates this approach:
In this code, we first define a
chunkSize
constant that specifies the maximum number of buttons perdiv
. Then, we usereduce
to split theaccounts
array into chunks ofchunkSize
or less. Each chunk is an array that contains up tochunkSize
accounts.Next, we use Pug’s
each
loop to iterate over the chunks, creating adiv
element for each one. Within eachdiv
, we use anothereach
loop to iterate over the accounts in the chunk and create abutton
element for each one.Note that we use the
slice
method to limit the number of buttons per chunk tochunkSize
, in case there are fewer thanchunkSize
accounts in the chunk.This should create the desired grouping of buttons inside
div
elements, with up to 10 buttons perdiv
.I would approach this with two loops and a conditional. It’s much more legible to me than a
.reduce()
method.The outer loop creates the appropriate number of container divs based on the length of the
accounts
array. If there’s 36 accounts, with 10 in a div, it will create 4 divs. (36 / 10 = 3.6, which rounds up to 4).Then the inner loop creates each button by accessing the appropriate index of the
accounts
array, if it exists.