Dynamically build a table

I want to create a table with n columns dynamically, where n is a counter value defined as

#let question-counter = counter("question")

So if I have two questions, I want the table to be

#let mainline() = align(center, table(
  columns: (2.6cm, 2.6cm),
  align: center,
  table.header(
    [Q1], [Q2], 
  ),
  [1.5], [1.5],
))

I have tried using a combination of question-counter.final().first() and

#(range(1, 2+1).map(i => "Q" + str(i))),

but I can’t seem to get a working solution.

I was able to figure it out (well through Gemini)

#context {
  // 1. Get the final value of the counter
  let count = question-counter.final(here()).first()
  
  // 2. Generate the table
  // We check if count > 0 to avoid errors if the document is empty
  if count > 0 {
    table(
      columns: count, // Create one column per question
      align: center + horizon,
      
      // 3. Generate Headers (Q1, Q2, etc.)
      ..range(1, count + 1).map(n => [*Q#n*]),
      
      // 4. Generate Empty Cells (bottom row)
      ..range(0, count).map(_ => [\ ]) 
    )
  }
}

I needed that context() there.

1 Like

Well done solving it yourself!

Do you really have the here() call in final()? I don’t think that’s valid and it’s not necessary.

I would also ask you to try to revise your post’s title to be a complete question as per the question guidelines:

Good titles are questions you would ask your friend about Typst.

We hope by adhering to this, we make the information in this forum easy to find in the future.

Also don’t forget to mark :ballot_box_with_check: it as the solution (once you have checked sijo’s feedback). Thanks!