Is it possible to show and hide text blocks based on a conditional?

I have writing an examination paper for my students in which I am simultaneously writing the solutions as well. When I am done, I’d like to simply set a flag which hides all the blocks with the solutions rather than me commenting each solution block out. Is it possible to do something like the following

flag_for_solution = false

*Question x.* Question statement

// solution block
if flag_for_solution 
   #block(fill: luma(230), inset: 8pt,radius: 4pt, width:100%) 
   [ 
     Solutions in this block
   ]
else don't show the block

For comparison purposes, I do something similar in latex using the comments package, which works something like this

\includecomment{solution}  # shows the block
\excludecomment{solution}  # hides the block

\begin{document}
   \begin{solution}
      Solution here
   \end{solution}
\end{document}

Hi @kfold3 welcome!

That’s definitely possible with Typst! You might find the documentation helpful, but your example code almost works.

#let flag_for_solution = false

*Question x.* Question statement

// solution block
#if flag_for_solution [ 
   #block(fill: luma(230), inset: 8pt,radius: 4pt, width:100%)[ 
     Solutions in this block
   ]
 ]
else don't show the block
Output


Thank you this is great.
As a matter of convenience, is it possible to make a shorthand for this? Something like

#define myblock = 
     #if flag_for_solution [ 
        #block(fill: luma(230), inset: 8pt,radius: 4pt, width:100%)[]

// and then I can just do 
#myblock[
   my text here
]

And thanks for the welcome! I just got started with Typst a few days ago, coming from a heavy latex background. I do wish that typst also allowed \ as a command prefix (i.e., \mu, \integral, \hat) which would really help with the muscle memory as well as copying/pasting long latex snippets. I also wish that the block math was $$ rather than a single $. But other than these minor inconveniences, I am loving it!

1 Like

Sure I was about to add it to my post above, here it is with the use of a function

#let flag_for_solution = true

#let solution(body) = if flag_for_solution {
  block(fill: luma(230), inset: 8pt,radius: 4pt, width:100%, body) 
}

*Question x.* Question statement

// solution block
#solution[
  Solutions in this block
]
else don't show the block

In addition to this technique, there are already a few packages based on it that may provide you with some additional desirable features, or inspiration on how to implement them. see here: search results for “exam”