Optional value in StringTemplate

You can use MissingQ instead of NumericQ:

template = StringTemplate["a is `a`<* If[!MissingQ[#b],\" and b is \",\"\"]*>`b`"];

Then:

template @ <|"a"->1|>
template @ <|"a"->1, "b"->2|>

"a is 1"

"a is 1 and b is 2"


Sorry for not using templates:

StringRiffle[ KeyValueMap[List]@<|"a" -> 1, "b" -> 2|>, " and ", " is "]

st[sub_] := If[KeyMemberQ[sub, "b"], StringTemplate["a is `a` and b is `b`"], StringTemplate["a is `a`"]]@sub;
st[<|"a" -> 1|>]
st[<|"a" -> 1, "b" -> 2|>]

"a is 1"

"a is 1 and b is 2"

ALTERNATIVE:

Or you could make it more easily scalable for more different cases by defining:

strings = {{"a", "a is `a`"}, {"b", " and b is `b`"}};
compose[strings_, sub_] := Block[{st = ""},
  Do[If[KeyMemberQ[sub, element[[1]]], st = st <> element[[2]]];, {element, strings}];
  StringTemplate[st]@sub
]

the strings variable contains snippets to be added when first element is present. The function compose checks all cases and constructs the template

compose[strings, <|"a" -> 1|>]

"a is 1"

and

compose[strings, <|"a" -> 1, "b" -> 2|>]

"a is 1 and b is 2"

just add more entries to strings as you wish.

Tags:

Templates