Indeed that’s how to do it, except for the “afterwards” part. Have you found the measure() function in the docs yet?
But you don’t want to render the whole document, and actually get data you can process in the rest of your pipeline. For that, you’d use typst eval.
The document could look like this:
#let measured(key) = {
let value = sys.inputs.at(key)
// embed metadata
context {
// this measurement uses the current styles, i.e. font, size, etc.
let width = measure(value).width.pt()
[#metadata(((key): width)) <width>]
}
// render value
value
}
#title(measured("title"))
#measured("text")
The pt() converts the length into a number; without it you get a string like "13pt", and you can use another unit if you want.
You’d query it like this:
$ typst eval 'query(<width>).map(it => it.value).join()' --in document.typ --input title=Hello --input text=World
{"title":46.880900000000004,"text":27.687}
Each it.value is a key: width pair, and the way joining works for dicts means you end up with a single dict with all the key/value pairs.
This is JSON output that you can process further. I’d actually recommend to use JSON input as well; I wrote a bit about options here: Can I configure my document (e.g. draft/release version, color theme) when creating a PDF without modifying the Typst file directly? - #3 by ensko
This looks like it renders the whole document, and it kinda does: you can be certain that the measurement is exactly what you’ll get when rendering, which means that all layouting and resolving (e.g. of bibliography items, references, etc.) is actually done. The actual rendering to PDF is saved though, so it’s a lot cheaper than saving a PDF, looking for the correct PDF element, and determining its width from PDF data, in case that’s what you meant with “measuring afterwards”.
If you want an even cheaper check, you’d either need to prepare a dedicated measurement document (e.g. exactly what I posted) that duplicates the styling so that measurements are correct, or you could pass a flag to the document so that expensive stuff is skipped when the document is used in a measurement.