ST condensed -- Templates and expressions

Skip to end of metadata
Go to start of metadata

Contents

Overview

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.

StringTemplate object, attributes, template text and expressions

As shown in the previous article, the StringTemplate object has the following features:

  • Attributes: Values, or references to data items in the calling program, which will be supplied to expressions during the template rendering process.
  • Template text: Consists of alternating:
    • Literal text: Text which will be copied directly to the result text
    • Expressions: which obtain values from the StringTemplate's attributes, and, with some processing, insert strings into the result text.

Expression delimiters: $...$ or <...>

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:

Example template text with <..> expression delimiters:

Where might you deal with template texts?

The same template text might come into play in several different places in an application that uses the StringTemplate library:

  • As a String in the calling language: Your application might create the template text as a string, and pass it to one of the StringTemplate constructors or StringTemplateGroup methods that create a StringTemplate.
  • In a template file -- xxx.st  You might provide templates in individual xxx.st files. The filename (minus ".st") provides the template name.
  • In a template group file -- xxx.stg: You might provide one or more xxx.stg files, which can define several templates. The template definitions in stg files use the same syntax for the template text per se, but add additional surrounding syntax to provide the template a name, and to declare formal arguments.
  • Within a template expression: The expression syntax includes the capability to define and invoke a (usually small) template on-the-spot within an expression. Once again the same syntax is used within the template text itself, but there is additional expression syntax around it, including the ability to specify arguments.

Simple templates

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
text:
Attributes supplied:
sometext = "Hello"
personname = "Fred Smith"
addr = "123 First St."
phonenum = "123-4567"
Result from
toString()
<b><i>Hello</i><b> Name: Fred Smith
Address: 123 First St.
Phone: 123-4567

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.

Templates defined in a string template group file

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.

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 Overview

The basic idea

Expressions:

  • make use of some input data, ultimately from attributes supplied to the StringTemplate object by the calling program
  • perform some processing
  • always return a string (or nothing)

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:

  • Expressions with no template section
  • Expressions with a template section

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.

Expressions containing no template section

This category covers the forms of expression like the following:

  • <attribname>
  • <attribname.propname>
  • <attribname; options>
  • ... and similar.

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.

  • If the attribute is already a string, it is returned as is (or as influenced by options) from this expression.
  • If the attribute is some other simple type, like integer, then its AsString() method is called to obtain a string
  • If the attribute refers to a list, then each of its items is individually turned into a string and concatenated to produce a result string. (An option can specify a separator to place between the items as they are concatenated).
  • If attribname refers to an object, and propname is also specified, then StringTemplate looks for a property corresponding to propname on the object supplied.
  • If attribname refers to a map object, then propname is used to "look up" that name in the map's key list, and return the corresponding value.

Expressions containing a template section

This category covers the forms of expression like the following:

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:

  • Attributes and Late stringification
    • The varieties of attributes/properties/maps which may be specified in the "select attrib(s)" section are as described above for the no-template expressions.
    • Attributes are passed into, or available to, the inner template without turning them into strings.
    • To make use of an attribute, ultimately, the inner template (or a template that it in turn invokes) has to have an expression of the no-template variety to convert the attribute to a string.
  • Iteration
    • If the attribute or property specifies a list, then the inner template is applied to each item in the list separately. That is to say, the inner template is invoked multiple times, each time supplying an item from the list. This will result in multiple returned strings from the inner template, which during render will be concatenated to form the outer template's result (possibly with a separator specified in options.)

Exact details of how attributes are passed to inner templates will be covered in sections below.

Variations for each part of an expression

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
  • Select an attribute (of the template)
  • Select a property of an object attribute
  • Select an attribute's property based on an expression
  • Select a value from a map
  • Look up an attribute value in a map
  • Select or create a list over which to iterate a template
  • Select or create multiple parallel lists over which to iterate a multi-argument template
  • Select or create a subset of a list (using operators)
  • Invoke a named template defined elsewhere in the group, or supergroup.
  • ... or define a template on-the-spot ("anonymous" template), and apply it.
  • Apply the template(s) to attributes from the "select attributes" part of the expression.
    • If the selected attributes are lists, invoke the template(s) for each item.
    • Selected attributes may be multiple parallel lists, with an item from each list supplied to each of multiple template arguments, for each iteration.
  • A template can also refer directly to attributes in the context of the containing template.
  • Multiple templates can be chained, passing results from one to the next (using colon syntax).
  • Multiple templates can be alternated, with a different template applied to successive items in a list (using comma syntax)
Mostly controls formatting of the string result of the template
  • Indent
  • Wrap
  • Separator between list items
  • What string to substitute for a value that's null
  • Passing options to a FormatRenderer

Examples

Category Select
Attribute(s)
(:)Template(s) ; options Examples
  - - -  
Convert attrib to string X - - <customer>
  X - X <customers; separator=", ">
         
Invoke inner template - X - <disclaimer(yr="2009", co=coname)>
  - X X <hitcount()>; format="fancy">
  X X - <customer:salutation()>
  X X X <customers:makebold(); separator=", ">

Expressions Intro HTML Version: GW  2009-06-24

Template Expressions and Statements

Documentation conventions

One of the significant challenges in describing syntax is to clearly distinguish between the following:

  • Parts of the syntax you type in verbatim. These are in typewriter font, non-italic ("upright").
  • Parts that are to be replaced by your own attribute names and so on. These are in italic typewriter font.
  • Almost no symbolsthat are not part of the syntax. (Some authors might use square brackets to indicate optional syntax, for example). The only such syntax on this page is the elipsis "...", used to indicate "fill in the usual stuff here". (Except where the elipsis is actually part of expression syntax, which is clearly noted.)

Symbol guide

Symbol
Meaning
  Symbol
Meaning
attrname Attribute name
  tmpname
Name of a template to be called from this one
(defined elsewhere in the current template's group)
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
     

Table of Template Expressions and Statements

_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.

Expressions

Syntax Description
Select Attributes  
<attrname> Insert the string value of the attribute named attrname
<attrname> If attrname is an attribute with multiple values, then insert the concatenation of these strings.
 
<attrname; separator=expr> (Semicolon: delimiter before specifying options.)
If attrname is an attribute with multiple values, then insert the concatenation of these strings separated by separator.
<attrname; format=expr> When invoking a StringTemplate equipped with a FormatRenderer, the tempate expression can pass a string argument to it (here expr), using the options part of the overall expression.
Multiple options can be provide, separated by comma, example:
<attrname; format="toUpper",separator=" and ">
<attrname.propname>
 
Dot = select property of attribute
Tells StringTemplate to look for property called propname on the variable that was supplied for attrname, and insert its string value here.
<attrname.(expr)> (expr) = indirection
Same as <attrname.propname>, except first evaluate expr to calculate propname.
<mapname.itemname> Look up a value in a map. (Maps are name:value tables defined by the calling program or in an stg file.) Here mapname specifies the name of the map, and itemname provides the name of the item to look up. Result will be the value field of that item in the table.
<mapname.(expr)> Same as <mapname.itemname>, except first evaluate expr to calculate itemname.
<[attrname1,attrname2]> Square brackets: Make a list that combines the single or multiple values of attributes attrname1 and attrname2. Such a list can be used wherever a multi-valued attrname can be used.
Invoke template  
<tmpname()> ( ) indicates that tmpname refers to a template to be invoked. In this case, invoke template named tmpname, without args (though the template can access attributes from the surrounding template's context). Insert resulting string.
<tmpname(argname=expr, argname=expr)> Invoke template named tmpname, with arguments. Insert resulting string.
-- argname refers to an argument of the called template (which in turn should match some attrname in an expression within the called template's text.)
-- expr can be any expression that makes sense in the context of the enclosing template. Note that an expression does not need to be delimited if it's inside an arg list. So:
Correct:      <mytemplate(somearg=someattr)> 
Incorrect:    <mytemplate(somearg=<someattr>)>
<tmpname(...)> Ellipses (three periods). The "..." syntax in the argument list says that template tmpname should obtain all argument values from the same-named values in the current template. (This overcomes the normal behavior of <tmpname()>, where any declared arguments of tmpname prevent tmpname's expressions from seeing the same-named values in the calling template.) Note: This is the only place in StringTemplate expressions that "..." is used as actual syntax. Elsewhere in this documentation, "..." stands for "et cetera".
<tmpname(argname1=expr,...)> Similar to preceding, but here a value for argument argname1 is provided explicitly, and the remaining arguments are "passed through".
  In the following: args represents: argname=expr,argname2=expr2 (etc)
<(expr)(args)> Template invocation, but first evaluate expr to calculate tmpname template name
Inheritance-related syntax  
<super.tmpname()> Invoke inherited template: For templates in a group that inherits from another group, invoke the supergroup's version of the template using the super keyword.
Note: Using a fully-qualified template name, (with actual name of the supergroup in place of "super") does not work in this situation.
Invoke template and apply it to an attribute In the following expressions, a template is applied to an attribute. Where the attribute has multiple values, the template is invoked multiple times, each time with the next value from attribute. The final result is the list of output strings catenated together into a single string.
<i>,  <i0> and <it> Each time the template is applied, the value of the attribute for this iteration is made available in the invoked template through the built-in expression <it>. The invoked template can see the number of the iteration in the built-in expressions <i> (counting from 1) and <i0> (counting from zero).
<attrname:tmpname(args)>
 
Colon: apply template to attribute. If the attribute has multiple values, invoke template tmpname once for each value. Within template tempname, the value of attrname can be obtained using <it>
Special shorthand case: If template tmpname declares exactly one formal argument, and that template is invoked without arguments like this:
<attrname:tmpname()>
then StringTemplate will assign the attribute value to both <it> and that single argument.
<attrname:(expr)(args)> Same as preceding, but first evaluate (expr) to calculate name of template. Eg: This could obtain template name from an attribute.
<attrname:tmpname(args); null="xxx"> Semicolon: delimiter beginning one or more options. Here the option is the null option which provides a string (or expression) to return if attribute attrname is null. (Default result would be null string.)
<attrname:tmp1name(args):tmp2name(args)... Colon. Apply each template in sequence left to right. In the leftmost template, the value of the attribute can be accessed using <it>. Each successive template can use <it> to access the result so far. If the attribute has multiple values, then each template passes a multi-value result to the next template, and finally to the result of this overall expression where it is catenated into a single string.
Define a subtemplate on-the-spot in an expression ("anonymous" template) and possibly apply it to an attribute
<...{tmptext}...> Braces: define template, returning a string. In general, an on-the-spot ("anonymous") template can be placed anywhere that an expression can appear. Ie: anywhere in this this article: substituting for (expr).
<attrname:{tmptext}> Invoke the "anonymous" template defined by tmptext to attribute attrname.  If the attribute is multivalued, then invoke tmptext once for each value.  Within tmptext, use <i>, <i0> and <it> as described above.
<{attrname:{argname | tmptext}> Invoke anonymous template (defined by tmptext) for each value of multi-valued attribute attrname. On each invocation, the value of attribute attrname is given to argname. Expressions within tmptext can refer to that value either using <argname> or <it>.
<attrname,attrname2:{argname,argname2 | tmptext} > "Parallel list iteration". Similar to the preceding, except two (or more) attributes are used for input, whose values on each iteration are given to the corresponding arguments:  attrname --> argname, attrname2 --> argname2, and so on.  This syntax can be extended to three or more attributes and arguments.
Having multiple arguments, this syntax does not define an <it> attribute. (However, if the surrounding context has an <it> attribute then it can be accessed within tmptext).
<attrname:tmp1name(),tmp2name()...etc Comma: Apply only one template from the list of templates, alternating for the multi values of attrname. First iteration invokes template tmp1name, second iteration invokes template temp2name and so on, wrapping around as many times as needed.
Operators  
<first(attrname)> Returns the first (or only) element in this multi-valued attribute
<last(attrname)> Returns the last (or only) element in this multi-valued attribute
<rest(attrname)> All but the first element of attribute attrname. Returns nothing if the attribute is single valued.  You can combine operations to say things like:
first(rest(names)) to get second element.
<trunc(attrname)> All but the last element of attribute attrname.
<strip(attrname)> Returns all elements that are non-null in attribute attrname.
<length(attrname)> Returns count of of elements in attribute attrname. Use length(strip(list)) to get count on non-null elements.
(Note: this length function does NOT return the character-count length of a string.)
<...expr1+expr2...> Plus: catenate two strings. Terence says he prefers the alternative of using a subtemplate:
<...{<expr1><expr2>}...>
Other operators or functions You might expect to find other operators or functions for manipulating strings, for example left/right padding, trunctation and so on. StringTemplate does not have these built in. Instead, see the FormatRenderer topic.
Escapes  
\$ or \< Whichever delimiter the template is using, if the template needs to use that character literally it can be escaped to avoid incorrect parsing.
<\ >, <\n>, <\t>, <\r> These expressions can be used for space, newline, tab and carriage-return. More than one of these can appear in a single <...> expression.
<\uXXXX> This expression can place a specific unicode character into the template. Example: <\u1234>.  More than one of these can appear in a single <...> expression.
Comment  
<! lorem !> or $! lorem !$ Comments, ignored by StringTemplate.
______________________________________  

Statements

Syntax Description
Conditional statements These constructs can be nested.
<if(attrname)> subtmptext1
<else> subtmptext2
<endif>
Tests attribute attrname to determine whether to include text subtmptext1 or subtmptext2.  The attribute test evaluates to true if one of the following is true:
-- attribute attrname is an object with a boolean value and is true
-- attribute attrname does not have a boolean value, but does have a value (is not null).
<if(attrname1)> subtmptext1
<elseif(attrname2)> subtmptext2
<elseif(attrname3)> subtmptext3
<else> subtmptext4
<endif>
Include the first subtemplate text for which the corresponding attribute is true (boolean true, or nonboolean and not null). 
<if(!attrname)> subtmptext1 <endif> Use exclamation point to indicate NOT.
Region markers  
<@regionname()> In a template of a supergroup, mark a location in the template; note use of brackets ( ), and no  <@end> marker.)
See File formats article for the string-template group file syntax for specifying the text to insert/substitute at a region.
<@regionname>
...template text...
<@end>
In a template of a supergroup, mark begin and end of a region of template text; no brackets ( ), and do use <@end> marker.
   
_________________________________  

Expressions and Statements HTML Version: GW 2009-06-10 02:36:56

Summary of expression options

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
separator="sep If multi-values are emitted from this expression, catenate them with separator between
format="formatstr 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.)
null="somestr For each null element in the input attribute, insert this string in the result.
wrap  Tell StringTemplate to wrap the output string if it exceeds the wrap length set in StringTemplate.toString(wraplen);.  (Note, no "=true", just the keyword wrap by itself.)
anchor="true"  If wrapping, then cause wrapped lines to indent so that they align with beginning of the first line of this template's output.

More template details

Template calling behavior

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:

  1. Look in this template's attribute table (applies if template is invoked directly by program code).
  2. Look in this template's arguments (applies if template is invoked by another template.)
  3. Look recursively up the chain of this template's calling templates for arguments/attributes that match
  4. Look recursively up the chain of this template's group / supergroup inheritance chain for a map

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().

String Formatting

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.)

Supplying attributes, revisited

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.

Simple String value

Example

... or...

Simple non-String value

Example

Any non-String is converted as need to a String, using that type's toString() method.

List of strings

Example

Calling setAttribute multiple times with the same attribute name causes that attribute to hold a list.

Aggregate type

An object with multiple fields (properties) can be passed as an attribute.

Template expressions that can access these properties:
StringTemplate does this using reflection and following certain rules, depending on the source code language. See the full Expressions article for details.

Aggregate built by addAttribute()

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.

Template expressions to access these properties:

Map

Another type of attribute value your program can supply is an object that implements the Map interface. Example:

Template expressions to access these properties:

Next: ST condensed -- File syntax

Labels:
None
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.