Sometimes it’s the little things that make a disproportionately big difference.
Several people have been making fairly big use of the Stringtree template system recently, both as part of Mojasef and for general purpose text generation. One of the things it’s particularly good at is rendering collections and sequences. For example, if there is an ArrayList of the Integers 1, 17 and -29 stored in the template context as “stuff”, then the following template will generate a comma-separated list of the values in brackets:
[${stuff*/','}]
The ${ and } indicate the start and end of a template token. Within the token stuff is the name of the context value, the * indicates that it should be “multiplied” (i.e, each element rendered in sequence), and the /’,’ indicates that the elements should be “divided” by commas.
Expanding this template gives:
[1,17,-29]
Now, this is all fine if the values in the collection can be directly output. Now imagine that we have a collection of three Strings: ‘hello’, ‘there’ and ‘world’, and we want to generate a similar sequence, but with each String surrounded by quotes. For this we need two templates:
[${stuff*quote/','}]
and a new tamplate (named quote.tpl)
"${this}"
In this case the collection is “multiplied” by the template “quote”, i.e, each element of the collection is placed in the context in turn as “this”, and the template “quote” is evaluated. The resulting values are then “divided” by the commas.
Expanding this template gives:
["hello","there","world"]
The astute amongst you will have noticed that all of the above can actually be done by JSONWriter, but the templating sytstem is much more flexible, and works just as well generating HTML, XML and any other text format.
Now to the point of this article. I have found it increasingly common when generating XML to want to emit a sequence separated by newlines. This can easily be done using the above syntax by giving a newline as a “divide” string:
[${stuff*quote/'
'}]
But this has always looked clumsy to me.
So, in Stringtree 2.0.7 I have finally got around to making a neater syntax for this. Now, if you use a / to indicate a “divide”, but do not supply a separator, the template system will default to a newline. If you don’t want any separators at all, you can still just leave off the /. So lets try the new, neater, way to write a newline-separated chunk of XML from the same collection of Strings:
<quotes>
${stuff*quote/}
</quotes>
and the template quote.tpl
<quote>${this}</quote>
Expanding this template gives:
<quotes>
<quote>hello</quote>
<quote>there</quote>
<quote>world</quote>
</quotes>
A very small change, but one which makes a common task a lot nicer.
As a side note, in 2.0.7 I also brought out from my dusty archives an old XML parser I wrote years ago and integrated it with the current Stringtree code base. Feel free to play with it, but I don’t really consider it ready for “prime time” yet.
Posted by Stringtree in Projects, Templater
