# How to use StringTemplate for code?

Say, I want to write a MMA script using StringTemplate, so I can insert additional pieces of code / expressions wherever TemplateSlots appear. It is a bit unclear to me, however, how I should handle these slots. For example the template

tmp = StringTemplate[
ToString[
Unevaluated[
Pi/2 + "a" + 2
],
InputForm
]
]


gives

tmp[<|"a" -> 1|>]
(* Pi/2 + "1" + 2 *)


That is, it looks like the parameter 1 is substituted as a String whereas it should be a number. This is not the case, however. What actually happens is, that 1 gets inserted, but the quotation marks in the template remain. So how should I declare TemplateSlots in my StringTemplate? It should work with any MMA code inside the Unevaluated.

• Perhaps OutputForm["a"] instead of "a"? – Carl Woll Aug 4 '17 at 4:52
• I'd not use StringTemplate here, check what happens for "a"->-1. – Kuba Aug 4 '17 at 6:28
• @CarlWoll: Yes, this seems to work! Thanks! I'd accept it if you post this as an answer. Much easier than I thought :-) @Kuba: There does not seem to be any problem with -1 (after applying ToExpression in the end). – JEM_Mosig Aug 4 '17 at 7:32
• @JEM_Mosig if there is ToExpression then why strings at all, why not go with TemplateObject? And if string step is needed then "Pi/2 + - 1" does not look well. – Kuba Aug 4 '17 at 7:52

As an alternative to Carl's method you can use:

StringTemplate["Pi/2 +  + 2"]["a"]

"Pi/2 + a + 2"


so

templ = StringTemplate[
StringTemplate["Pi/2 +  + 2"]@"a"
];

templ @ <|"a" -> 2|>

"Pi/2 + 2 + 2"


but for "a" -> -1 you will get

"Pi/2 + -1 + 2"


so I'd suggest full TemplateObject mode:

TemplateObject[
TemplateExpression[
ToString[Unevaluated[Pi/2 + TemplateSlot["a"] + 2], InputForm]
]
] @ <|"a" -> -1|>

"Pi/2 - 1 + 2"


or

TemplateObject[
Hold[Pi/2 + TemplateSlot["a"] + 2]
, CombinerFunction -> (ToString[#, InputForm] &@*Apply[Unevaluated])
] @ <|"a" -> -1|>