This article attempts to cover and update (2009-06) all the material in the users guide Expressions article and the current Cheat-Sheet's Expressions section.
As shown in the previous article, the StringTemplate object has the following features:
StringTemplate can recognize a choice of different delimiters around expressions, with $...$ and <...> being the two built-in alternatives. (The choice must be set by the calling program before invoking a template.) Be aware that documentation might show examples with either expression delimiter, $...$ or <...>.
Example template text with $..$ expression delimiters:
blah blah blah $an expression$ blah blah blah $an expression$ blah blah blah $an expression$ blah blah blah |
Example template text with <..> expression delimiters:
blah blah blah <an expression> blah blah blah <an expression> blah blah blah <an expression> blah blah blah |
The same template text might come into play in several different places in an application that uses the StringTemplate library:
The following example illustrates a couple of simple templates. Note use of alternative expression delimiters.
|
Example: Apply html bold-italic to a string |
Example: Format some personal info |
||
---|---|---|---|---|
Template |
|
|
||
Attributes supplied: |
sometext = "Hello" |
personname = "Fred Smith" |
||
Result from |
<b><i>Hello</i><b> |
Name: Fred Smith |
The template texts shown here could be provided as a string when creating a StringTemplate calling a StringTemplate constructor. Alternatively, the template text could be provided from a file, perhaps bold-italic.st, or personalinfo.st, for the examples here.
This example shows a snippet from a string template group file (xxx.stg). It's the definition of a template called personalinfo(), which has the same template text as the preceding example, but declares three formal arguments.
personalinfo(personname,addr,phonenum) ::= << Name: <personname> Address: <addr> Phone: <phonenum> >> |
Here again either <...> or $...$ can be used for the expression delimiters within the template text (matching whatever the corresponding StringTemplate object is set to recognize). Note that this is a separate issue from the <<...>> delimiters around the overall template text -- there is no alternative for these. The formal arguments and the <<...>>> delimiters are syntax particular to xxx.stg files, and are not allowed in individual xxx.st files.
Expressions:
It is possible to create very elaborate expressions, but at heart an expression has the following basic structure.
There are three basic parts, and they are each optional. By using or not using each part, expressions can serve various purposes. It is useful to distinguish two main varieties of expression:
The following sections give a general overview of these varieties of expressions. The syntax is spelled out in detail in a section "Table of Template Expressions and Statements" below.
This category covers the forms of expression like the following:
<attribname>
<attribname.propname>
<attribname; options>
These are the forms of expression where an attribute is actually read from the calling program and turned into a string, as sketched in the following diagram.
Note that in StringTemplate there are no local variables, nor any calculations based on attribute values, except for map lookup. Consequently, all values come directly from attributes or maps, positioned in the flow of result text by these no-template expressions.
The options section controls formatting of the string result.
This category covers the forms of expression like the following:
<templatename()> <attribname:other_template_name()> <attribname:{template text}> ... and similar. (An option section may be present too.) |
In these cases, the inner template obtains inputs either from the attribute specified by attribname, or from the surrounding template (or both). Where there is an attribname section, the template is said to be "applied to" this attribute. The following diagram summarizes:
Notes:
Exact details of how attributes are passed to inner templates will be covered in sections below.
The following table summarizes the variations available for each of the three sections of the expression. Remember that if the template part is present, the "specify attribute(s)" part supplies attributes to the template. If the template part is not present, the "specify attribute(s)" part selects attributes to be transformed and possibly concatenated into a single result string.
Select attribute(s) part |
Template(s) part |
Options part |
---|---|---|
|
|
Mostly controls formatting of the string result of the template
|
One of the significant challenges in describing syntax is to clearly distinguish between the following:
typewriter font
, non-italic ("upright").italic typewriter font
."...",
used to indicate "fill in the usual stuff here". (Except where the elipsis is actually part of expression syntax, which is clearly noted.) Symbol |
Meaning |
|
Symbol |
Meaning |
---|---|---|---|---|
attrname |
Attribute name |
|
tmpname |
Name of a template to be called from this one |
expr |
An expression. Do not surround with delimiters when expr appears directly within an expression (as opposed to within a template.) |
|
argname |
Name of an argument of a template to be called from this one |
propname |
Name of a property of an attribute |
|
args |
Shorthand for argname=expr, argname2=expr2 |
mapname |
Name of a map |
|
tmptext |
Text of a template defined within an expression "on-the-spot" ("Anonymous" template.) |
itemname |
Name of an item in a map |
|
|
|
<DIV mce_style="page-break-before: always;" style="page-break-before: always;"></DIV> |
_Wiki note: The following table is included from a separate html file as the many collisions between StringTemplate expression syntax and wiki markup syntax make editing in the wiki impractical.
The following table summarizes options that may be placed in an expression, following a semicolon:
<blahblah;option1,option2>
. Example: <SomeAttrib;separator=", ", null="blank">
Option |
Description |
---|---|
|
If multi-values are emitted from this expression, catenate them with separator between |
|
String to pass to an AttributeRenderer as an argument specifying format details. (Specific formatstr strings are determined by whatever is recognized by the particular renderer.) |
|
For each null element in the input attribute, insert this string in the result. |
|
Tell StringTemplate to wrap the output string if it exceeds the wrap length set in StringTemplate.toString(wraplen);. (Note, no "=true", just the keyword |
|
If wrapping, then cause wrapped lines to indent so that they align with beginning of the first line of this template's output. |
The syntax for defining a template in a string template group file might suggest that when one template invokes another, data is passed only via the arguments, like calling a function in other languages such as Java. However this is misleading.
In actuality, when one template invokes another, StringTemplate passes the context of the caller to the called template. That is to say, not only does the called template get its arguments "filled in", but also the called template's expressions can see and refer to the attributes or arguments that are in the scope of the caller template. This behavior is much more like C macros, or like closures in some other languages.
User guide article Template and attribute lookup rules has the details, but in summary, StringTemplate follows the order below in resolving attribute names in expressions:
A further wrinkle is that a template's argument list normally "hides" any attribute or argument of the same name in the caller template's scope. For variations on how to subvert this, see the "..." expression syntax, and also StringTemplate.setPassThroughAttributes().
StringTemplate provides no built-in string formatting functions per se, such as string truncate, or left/right pad, or number formatting. Instead, the application must provide data to an attribute as an already-formatted string, or the calling program can attach AttributeRenderer objects to provide formatting capabilites to the template world. This is done through the AttributeRenderer features. An application may attach AttributeRenderers to a StringTemplate which apply to specific attribute datatypes or classes of objects. When an object of such a type or class is supplied as an attribute to a StringTemplate, the related AttributeRenderer will be invoked when the template gets rendered.
AttributeRenderers may be designed to accept arguments from the template expression: The template expression provides these through the format option. (See Expression sytax table).
The AttributeRenderer for the String type is special: This will be invoked not just for String attributes, but also for inner template results (which return a string). You can consider creating and attaching an AttributeRenderer which provides generally-useful string functions. (Someone should write a how-to on this. There's an example in John Snyder's STST.)
When a template is prepared by an application, part of the process involves supplying Attributes (named values) using the StringTemplate.setAttribute() method (or related). There are several variants on that procedure, detailed here.
Example
MyTemplate.setAttribute("someattrname","somevalue"); |
... or...
String s = "Blah blah"; MyTemplate.setAttribute("someattrname",s); |
Example
int x = 123; MyTemplate.setAttribute("someattrname", x); |
Any non-String is converted as need to a String, using that type's toString() method.
Example
MyTemplate.setAttribute("names", "Fred"); MyTemplate.setAttribute("names", "Mary"); MyTemplate.setAttribute("names", "Chris"); |
Calling setAttribute multiple times with the same attribute name causes that attribute to hold a list.
An object with multiple fields (properties) can be passed as an attribute.
user.setUname("fred"); user.setEmail("fred@jones.com"); ... MyTemplate.setAttribute("userinfo", user); |
Template expressions that can access these properties:
User: $userinfo.uname$ has email $userinfo.email$ |
StringTemplate does this using reflection and following certain rules, depending on the source code language. See the full Expressions article for details.
If you want to present data to setAttribute in a structure, but don't already have a suitable aggregate data type, then you can create one in the call to setAttribute, like the following example. This shows how to set multiple properties at once. The values supplied here are string constants, but variables can be supplied too.
MyTemplate.setAttribute("userinfo.{uname, email}", "fred", "fred@jones.com"); |
Template expressions to access these properties:
User: $userinfo.uname$ has email $userinfo.email$ |
Another type of attribute value your program can supply is an object that implements the Map interface. Example:
HashMap cust = new HashMap(); cust.put("custname", "fred"); cust.put("phone", "123-4567"); MyTemplate.setAttribute("custinfo", cust); |
Template expressions to access these properties:
Customer: $custinfo.custname$ has phone $custinfo.phone$ |
Next: ST condensed -- File syntax