How can I perform a boolean comparison on a context value returned from a function in Typst?

How can I perform a boolean comparison on a function’s return value in Typst? For example:

#let demo() = context {
    return true
}

#if demo() == true {}

This won’t enter the if block, because I found that the return type of the demo function is content. How can I convert it?

context always produces content, and you can’t extract anything from it. You have to but all code that depends on the contextual value inside the same context block. The below post explains context a bit.

2 Likes

Thank you, I think I got it.

Hi. The TL;DR is usually to hoist the context:

#let demo() = true
#context if demo() == true {}

Or better yet: don’t use it in the first place if absence of context doesn’t give you any errors or unexpected result.

From the docs:

In return, the context expression itself ends up opaque. We cannot directly access whatever results from it in our code, precisely because it is contextual […]

The other harder solution is to use state or metadata with label to save some data in the context scope and then retrieve it through state or query. But they also require context scope. And you need to place that (state/metadata) result in the document before trying to get the underlying data. And the new context must start after the placed-in-document data.

Yes, this really works.

#context if counter("heading").at(<end>).at(0) > 0 {}

Before your explanation, I didn’t realize that a context block will always generate content.