Skip to main content
Improved code in final example
Source Link

I can use a string template like so:

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

which gives

"a is 1 and b is 2"

But I would like the parameter b to be optional, so that if I call

st @ <|"a" -> 1|>

I get simply

"a is 1"

Something like this is possible with <* *>: For the case where b must be numeric, I can use

StringTemplate["a is `a`<* If[NumericQ[#b],\" and b is \"<>ToString[#b]\",\"\"]*>"]\"\"]*>`b`"]

but is there a way to tell whether a template parameter is present or absent, rather than numeric or otherwise?

I can use a string template like so:

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

which gives

"a is 1 and b is 2"

But I would like the parameter b to be optional, so that if I call

st @ <|"a" -> 1|>

I get simply

"a is 1"

Something like this is possible with <* *>: For the case where b must be numeric, I can use

StringTemplate["a is `a`<* If[NumericQ[#b],\" and b is \"<>ToString[#b],\"\"]*>"]

but is there a way to tell whether a template parameter is present or absent, rather than numeric or otherwise?

I can use a string template like so:

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

which gives

"a is 1 and b is 2"

But I would like the parameter b to be optional, so that if I call

st @ <|"a" -> 1|>

I get simply

"a is 1"

Something like this is possible with <* *>: For the case where b must be numeric, I can use

StringTemplate["a is `a`<* If[NumericQ[#b],\" and b is \",\"\"]*>`b`"]

but is there a way to tell whether a template parameter is present or absent, rather than numeric or otherwise?

Source Link

Optional value in StringTemplate

I can use a string template like so:

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

which gives

"a is 1 and b is 2"

But I would like the parameter b to be optional, so that if I call

st @ <|"a" -> 1|>

I get simply

"a is 1"

Something like this is possible with <* *>: For the case where b must be numeric, I can use

StringTemplate["a is `a`<* If[NumericQ[#b],\" and b is \"<>ToString[#b],\"\"]*>"]

but is there a way to tell whether a template parameter is present or absent, rather than numeric or otherwise?