How to conditionally display table rows based on if condition

Hey Guys,

I am trying to display lines in a table depending on a condition.

If ConnectorCustomerPN != "", the line shall be present.
If ConnectorCustomerPN == "", the line shall be omitted.

I am trying around with the below code, but I am getting diverse strange errors and cannot make it work. In the below variant, I get an “expected block” error on the last closing square bracket in the conditional line.

I also tried with table.cell(), but I could not make this work either.

#figure(
  caption: [connector properties],
  table(
    columns: (7cm, 5cm),
    align: (left, left),
    [*Item*], [*Property*],
    [Connector], [#ConnectorVariant], 
    [Type], [#ConnectorType], 
    [Number of Terminals], [3],
    if ConnectorCustomerPN != ""[[#Customer Part Number], [#ConnectorCustomerPN], ],
    [Recommended min. cross section for power-supply harness], [#ConnectorRecomCrossSection mm²],
  )
) <Tab_Connector_PartDescription>

How can I make it work?

Hi! It’s easier to help when you provide a complete minimal example that we can run (e.g. with all variables defined). Anyway in this case I think you just need to have the if return either an array or none, and use the spread operator to insert that in the list of table arguments:

..if ConnectorCustomerPN != "" { ([#Customer Part Number], [#ConnectorCustomerPN]) },
2 Likes

Here is how I would do it:

#let Connector-Rows(variant, type, num-terminals, pn-Customer, cross-section) = {
  let cells = (
    //Variant
    table.cell[Connector], table.cell(variant),
    //Type
    table.cell[Type], table.cell(type),
    //Terminal count
    table.cell[Number of Terminals], table.cell(str(num-terminals)),
    //Optional customer part number - will be removed later
    ..if pn-Customer == "" {
      (none, none)
    } else {
      (table.cell[Customer Part Number], table.cell(pn-Customer))
    },
    //Cross section
    table.cell[Recommended min. cross section for power-supply harness],
    table.cell[cross-section mm²]
  )

  //Remove unused rows
  let filtered-rows = cells.filter(cell => cell != none)
  return filtered-rows
}

#figure(
  caption: [connector properties],
  table(
    columns: (7cm, 5cm),
    align: (left, left),
    [*Item*], [*Property*],

    ..Connector-Rows("A Variant", "A Type", 3, "", 3),
  )
) <Tab_Connector_PartDescription>

The function takes in details about the connector and creates an array of table.cells. The optional row is removed from the array, then the array is returned to be placed in the table. But an array on its own can’t be displayed by the table so spread (..) is placed before it.

1 Like

Thanks! That worked!

I had tried the spread operator, but then I believe I had something wrong with the brackets on the right…

1 Like