skip to Main Content
    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


  1. You can achieve this grouping of buttons inside a div by using Pug’s each loop and slice method to split the accounts array into chunks of 10 or less. Then, you can wrap each chunk of buttons inside a div element using Pug’s string interpolation and iteration capabilities.

    Here’s an example code snippet that demonstrates this approach:

    div#container
      - const chunkSize = 10
      each chunk, index in accounts.reduce((acc, cur, i) => {
        const chunkIndex = Math.floor(i / chunkSize)
        if (!acc[chunkIndex]) {
          acc[chunkIndex] = []
        }
        acc[chunkIndex].push(cur)
        return acc
      }, [])
        div
          each account in chunk.slice(0, chunkSize)
            button #{account.stuff}
    

    In this code, we first define a chunkSize constant that specifies the maximum number of buttons per div. Then, we use reduce to split the accounts array into chunks of chunkSize or less. Each chunk is an array that contains up to chunkSize accounts.

    Next, we use Pug’s each loop to iterate over the chunks, creating a div element for each one. Within each div, we use another each loop to iterate over the accounts in the chunk and create a button element for each one.

    Note that we use the slice method to limit the number of buttons per chunk to chunkSize, in case there are fewer than chunkSize accounts in the chunk.

    This should create the desired grouping of buttons inside div elements, with up to 10 buttons per div.

    Login or Signup to reply.
  2. I would approach this with two loops and a conditional. It’s much more legible to me than a .reduce() method.

    - const numberPerDiv = 10
    #container
      - for (let i = 0; i < Math.ciel(accounts.length / numberPerDiv); i++)
        div
          - for (let j = 0; j < numberPerDiv; j++)
            if accounts[i + j]
              button #{accounts[i + j].stuff}
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search