I think this is a perfect use case of Evaluate Function – Typst Documentation — you want to generate typst code and the possible expressions are limited.
#let expr(n) = {
"sum_(i=1)^{n} i =".replace("{n}", str(n))
for i in range(1, n) {
"& {i} + \ ".replace("{i}", str(i))
}
"=& {}.".replace("{}", str(n * (n - 1) / 2))
}
#eval(expr(6), mode: "math")
You may also generate it more programmatically as below, but I don’t think that would be more reliable than eval.
#{
let align-point = $&$.body
math.equation({
import sym: eq, plus
eq
align-point
"1"
plus
linebreak()
align-point
"2"
plus
})
}

See also Pack complex content with data loading functions in Tips on debugging Typst code, including the dark magic
#raw(
yaml.encode($= &1 + \ & 2 +$),
lang: "yaml",
)
func: equation
block: false
body:
func: sequence
children:
- func: symbol
text: =
- func: space
- func: align-point
- func: text
text: '1'
- func: space
- func: symbol
text: +
- func: space
- func: linebreak
- func: space
- func: align-point
- func: space
- func: text
text: '2'
- func: space
- func: symbol
text: +
