How to add page numbers only if document length exceeds one page?

Simple question here: In order to make a template more flexible, I would like to include page numbers if and only if the document has more than one page. How do I do this? The following code leads to an error (“variables from outside the context expression are read-only and cannot be modified”):

#set page(width: 5cm, height: 5cm)
#let page-numbering = none

#context {
  if counter(page).final().first() > 1 {
    page-numbering = "1"
  }
}

#set page(numbering: page-numbering)

text on first page

#pagebreak()

text on second page

I couldn’t find a way to scope context only around the if-condition either :woman_shrugging:, e.g. like so:

#if context counter(page).final().first() > 1 {
  page-numbering = "1"
}

If you really want to “disable” the numbering for a single page, you can use the following function

#let page-numbering(i, last) = if last > 1 { numbering("1", i) }
#set page(numbering: page-numbering)

Typst automatically passes the current value of the page counter and the last value of the page counter to the numbering function. I would expect this to be equivalent to looking up counter(page).last().

As an alternative, you could also hide the page number in the footer (or wherever you are currently displaying it).

#let page-footer = context {
  if (counter(page).final().at(0) > 1) { counter(page).display() }
}
#set page(footer: page-footer)
2 Likes

The same logic works well if you express it this way:

#set page(width: 5cm, height: 5cm)
#show: doc => context {
  set page(numbering: "1") if counter(page).final().first() > 1
  doc
}
1 Like