For future posts, please make sure your title is a question you’d ask to a friend about Typst. Also, don’t forget to add some tags related to your post!
You should be using query() to retrieve the latest heading. It does ultimately require being in a context block, but in general you will only add the context block around the code where you actually need that information, so no need to be too hasty with it. In other words, don’t write let x = context { query() }; let y = func(x); y as you wouldn’t be able to access what query() returns (This would be an error); write context { let x = query(); let y = func(x); y } instead.
Here’s a full example:
#let template() = context {
let headings = query(selector(heading).before(here()))
let level = if headings.len() > 0 { headings.last().level } else { 0 }
heading(level: level + 1)[Template title]
[Some more stuff]
}
// Demo
#set heading(numbering: "1.")
#outline()
= My heading
#template()
== Other heading
#template()