How to pass a variable number of parameters to a table?

Hi,

Just for context : I am trying to generate a template from my rust code.
I have this template in which I can inject data in the variable using this lib : crates.io: Rust Package Registry

In fact, I have a problem when I want to use the content value that I define, in a for, in a table like this :

#import sys: inputs

#set page(paper: "a4", flipped: true)

#let content = inputs.v

#table (
  columns : 4,
#for (i, elem) in content.enumerate() {
  cell(#elem.heading),
  cell(Text: #elem.text),
  cell(Num1: #elem.num1),
  cell(Num2: #elem.num2),
}
)

Is there a way to generate a table according to a variable we define please ?

With this modification to your syntax, it should work.

I’m using mocked data since the web app does not have access to your inputs.

#import sys: inputs

#set page(paper: "a4", flipped: true)

//#let content = inputs.v

#let content = (
  (heading: [A], text: "A", num1: 1, num2: 2),
  (heading: [B], text: "A", num1: 1, num2: 2),)

#let cell = table.cell
#table(
  columns : 4,
  ..for (i, elem) in content.enumerate() {
    (cell(elem.heading),
      cell[Text: #elem.text],
      cell[Num1: #elem.num1],
      cell[Num2: #elem.num2],
    )
  }
)

Important modifications

  1. Every iteration of the for loop creates an array with the (..., ..., ...) syntax
  2. Typst implicitly combines all arrays in a for loop, according to the rule for blocks: Scripting – Typst Documentation
  3. Use the .. operator to spread the array of cells as arguments to the table. Note the table wants each cell as a separate argument. .. creates one function parameter per array element
  4. Note that the function table.cell is not mandatory but it can be used to set options for a table cell. For content, it takes a single parameter only.
  5. Note that the table takes the cells in row major order… rows are filled out first. So here, each iteration of the loop turned into one row.

1 Like

Thank you very much for your time and the quality of you answer !!!
You just saved my day.

Is it possible to do the same think with the table.header ?
I have values in my variable as a array… and I want for each one to add a header column name ?

Or, maybe I can put my value as the first row… and not using table.header…

Same with table.header, it can take input from an array of elements: table.header(..elements)

You would usually import table: ....

Hm, that looks unnatural to me

Well, if you didn’t use it, that is. It’s in the docs, and is the most concise. Just like import calc: min, max.

My objection is that table is documented as being an element, it does not say that it’s a module. So it seems like an easter egg that we can import like that, but now I’ve seen it, will digest.