How to conditionally define a 'watermark' variable?

I want to have a conditional watermark based on a command line parameter but am having trouble with the watermark variable being out of scope in the #set page call. Is there way to do this?

#if sys.inputs.watermark == "true" [
  #let watermark = rotate(24deg, text(185pt, fill: rgb("FF0000"))[*SAMPLE*])
] else [
  #let watermark = none
]

#set page(
  paper: "a4",
  numbering: "1",
  flipped: true,
  margin: 1cm,
  foreground: watermark
)

try setting the variable before the conditional:

#let watermark = none
#if sys.inputs.watermark == "true" { 
watermark = rotate(24deg, text(185pt, fill: rgb(“FF0000”))[SAMPLE])
}
#set page(
paper: "a4",
numbering: "1",
flipped: true,
margin: 1cm,
foreground: watermark
)
1 Like

Hey @Brent, welcome to the forum! I’ve changed your question post’s title to better fit our guidelines: How to post in the Questions category

Make sure your title is a question you’d ask to a friend about Typst. :wink:

I’ve also updated your post to use ```typ ``` around your Typst source code for better display, as @NNS did in their answer. It’s a neat trick! :smile:

1 Like

You can “factor out” the variable definition, because each block in Typst joins and returns each line in it. For example, #let x = { [a]; [b]; [c] } (where ; is equivalent to writing them in separate lines) will be the same as #let x = [abc]. With that in mind, we can write this:

#let watermark = if sys.inputs.watermark == "true" {
  // 'rotate(...)' is returned by this block
  rotate(24deg, text(185pt, fill: rgb("FF0000"))[*SAMPLE*])
} else {
  // 'none' is returned by this block
  none
}

#set page(
  paper: "a4",
  numbering: "1",
  flipped: true,
  margin: 1cm,
  foreground: watermark
)
1 Like