3
$\begingroup$

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.

$\endgroup$
4
  • 3
    $\begingroup$ Perhaps OutputForm["`a`"] instead of "`a`"? $\endgroup$
    – Carl Woll
    Commented Aug 4, 2017 at 4:52
  • $\begingroup$ I'd not use StringTemplate here, check what happens for "a"->-1. $\endgroup$
    – Kuba
    Commented Aug 4, 2017 at 6:28
  • $\begingroup$ @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). $\endgroup$
    – JEM_Mosig
    Commented Aug 4, 2017 at 7:32
  • 1
    $\begingroup$ @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. $\endgroup$
    – Kuba
    Commented Aug 4, 2017 at 7:52

1 Answer 1

4
$\begingroup$

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|>
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.