4

I was pleasantly surprised to find out that StringTemplate appears to work with styled (formatted) strings, with the style of the slots applied to the inserted expressions:

enter image description here

(The string was formatted using the Format menu.)

Is this usage intended or documented?

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371

1 Answers1

3

I think this follows from the representation of styles (and other boxes) in strings.

For example, this:

Mathematica graphics

is really represented like this in a string:

template="a \!\(\*\nStyleBox[\"``\",\nFontColor->RGBColor[1,0,0]]\) and a ``" 

Then either with StringForm or StringTemplate we get

enter image description here

In[10]:= StringTemplate[template]["foo", "bar"]

Out[10]= "a \!\(\*StyleBox[\"foo\",\nFontColor->RGBColor[1, 0, 0]]\) and a bar"

It's just plain substitution.


EDIT: This view also gives ideas on how to break substitution:

enter image description here

It appears that there is no special support for styling, it's all a side effect of how style boxes are encoded in strings.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263
  • Do you get the same error that I reported? – Mr.Wizard Feb 11 '15 at 21:37
  • 1
    @Mr.Wizard If I try to convert it by typing into it then yes, I get the error. Furthermore, the string is corrupted. If I convert it by changing the cell style then everything is fine. – Szabolcs Feb 11 '15 at 21:41
  • 1
    @Mr.Wizard Further testing shows that the error is not related to StringTemplate. Just make a styled string, evaluate it, and try typing in the output cell. The cell contents will be corrupted and the error appears. – Szabolcs Feb 11 '15 at 21:42
  • Thank you. I should have explored that further before posting. – Mr.Wizard Feb 11 '15 at 21:43