Can a function passed as argument to a grid know about the number of rows?

I want to style the last row of a grid (or table) differently than the rest. Let’s say I want it to have a red background and consider the following example:

#grid(
  columns: 2,
  fill: (x, y) => {
    let number_of_rows = 2
    if y == (number_of_rows - 1) {red}
    else {white}
  },
  [Entry 1], [Entry 2], [Entry 3]
)

Now, of course, with this everything works fine. However, as I add more entries to my grid (and more rows appear) the condition will be wrong and I’ll need to adapt number_of_rows. While this might possible (though bothersome) in my own document, it doesn’t work at all when writing a template.

Hence, the question: Is there any way to check in a function passed as an argument to a grid whether I am in the last row of the grid or not?

1 Like

Hello @junjios , this seems to be a duplicate of How can I format the last row of a table? - #6 by gezepi (tables and grids behave mostly the same way).

See the various solutions / workarounds.

Edit: This adapted from Discord works. But there are certainly cases where it will break. You can replace table with grid as needed.

#show table: it => {
  let cols = it.columns.len()
  let cells = it.children.len()

  let rows = calc.floor(
    cells / cols
      + calc.rem(
        cols - calc.rem(cells, cols),
        cols,
      ),
  )

  show table.cell.where(y: rows - 1): set text(blue)

  it
}

#table(
  columns: 2,
  ..for n in range(4) { (str(n),) }
)

1 Like