Five minute Introduction
examples are for v3 not v4
This short introduction to StringTemplate will hopefully help you answer the following:
- What is StringTemplate?
- What does StringTemplate do?
- What can I do with StringTemplate?
- How do I get started using StringTemplate?
- Where do I learn more about StringTemplate?
What is StringTemplate?
StringTemplate (or ST) is a template engine library used for generating text from data structures. The first version was developed for the Java platform and has evolved over the years of it's use on the jGuru.com website. StringTemplate's distinguishing characteristic is that it strictly enforces model-view separation unlike other comparable template engines. It is particularly good at multi-targeted code generators, multiple site skins, and internationalization/localization.
Independent implementations of some versions of StringTemplate are available in C# and Python (discussions about Objective-C and C++ implementations of StringTemplate occur frequently on the mailing list). StringTemplate is currently used to generate the ANTLR website and the StringTemplate website. It is also the engine that powers the powerful, flexible, multi-language, retargetable code generator in the ANTLR v3 language tool generator.
What does StringTemplate do?
Structured text generation. StringTemplate supports the generation of structured text output such as web pages, source code, emails and newsletters from arbitary data structures without sacrificing model-view separation.
StringTemplate is non-intrusive and doesn't require your data structures to implement any specific contracts. It is designed to be embedded inside other applications and is distributed as a small library with no external dependencies except ANTLR (used for parsing the StringTemplate template language) and, the standard platform libraries (e.g. JDK 1.2 for the Java version).
Why should I use StringTemplate?
To ensure the separation of the specification of business logic and computation required to generate structured text from the specification of how that text is presented (i.e. it's formatting).
For web developers, this translates to ensuring that a web page's business and persistence logic is separated from the the page's presentation.
For developers involved in code generation, this translates to ensuring generation and persistence logic is separated from output code structure. This separation directly supports the development of retargetable code generators.
Other benefits of model-view separation:
- Encourages the development of templates that are reusable in similar applications
- Unentangled templates serves as clear documentation of the generated code structure
- The templates (and hence the output or view) can be changed independently. Using more than one set of such templates is the basic mechanism for retargetable code generation
How do I use StringTemplate?
1. Get StringTemplate
Download and install StringTemplate from the download page on the StringTemplate website
2. Learn basic StringTemplate syntax
Please note that:
- each example in the table below fits on a single line but, it may appear on more than a line in the table due to space restrictions and wrapping.
StringTemplatesupports the use of<...>and$...$as delimiters (as shown in the examples)
Syntax |
Description |
Example |
|---|---|---|
<attribute> |
Replaced with value of attribute |
|
<attribute.property> |
Replaced with value of property of attribute (or empty string if missing). |
|
<attribute.(expr)> |
Indirect property lookup. Same as attribute.property except value of expr is the property name. |
|
<multi-valued-attribute> |
Concatenation of |
|
<multi-valued-attribute; separator=expr> |
Concatenation of |
|
<template(argument-list)> |
Include (i.e. call) template. argument-list is a list of attribute assignments of the form arg-of-template=expr. expr is evaluated in the context of the surrounding template not of the invoked template. |
|
<attribute:template(argument-list)> |
Template application. The optional argument-list is evaluated before application. The default attribute it is set to the value of attribute. If attribute is multi-valued, it is set to each element in turn and template is invoked |
|
<attribute:{argument-name_ | _anonymous-template}> |
Apply an anonymous template to each element of attribute. Set the argument-name to the iterated value and also set |
|
<if(!attribute)>subtemplate<endif> |
If attribute has no value or is a |
|
|
escaped delimiter prevents |
|
|
special characters: space, newline, tab, carriage return. |
|
|
Comments, ignored by StringTemplate. |
|
3. Create and use a template in code
Where better to start than a StringTemplate version of the ubiquitous "Hello, World" example... ![]()
Starting with version 2.3, StringTemplate uses <..> as it's default delimiters. For completeness, we will use $..$ here to illustrate how specific delimiters are specified with StringTemplate.
Java |
|
|---|---|
C# |
|
Python |
|
Python |
|
4. Create and use a template from a file
First, create the homepage.st template file as shown below and save it to a location on your system.
| homepage.st
|
Next, create the code that loads and uses the template file. To do so, we will make use of the StringTemplateGroup class that manages external templates.
java |
|
|---|---|
C# |
|
Python |
|
Python 3 |
|
What next?
Read the StringTemplate Documentation
Browse the list of questions frequently asked about StringTemplate
Your five minutes are up!
If this guide has been helpful to you, please consider contributing to this wiki when you are more familiar with StringTemplate.
Thanks
6 Comments
Hide/Show CommentsJun 23, 2009
John Doe
I ran the following code:
StringTemplate helloAgain = new StringTemplate("$rest(friends); separator=\", \"$", DefaultTemplateLexer.class);
helloAgain.setAttribute("friends", "Ter");
helloAgain.setAttribute("friends", "Kunle");
helloAgain.setAttribute("friends", "Micheal");
helloAgain.setAttribute("friends", "Marq");
System.out.println(helloAgain.toString());
and Ter did not want to be my friend, unless I did a call helloAgain.setAttribute("friends", ""); in front of it.
PS: Sorry, having trouble styling this comment, but I suppose you get the point.
Edit: using StringTemplate version 3.2
Jun 24, 2009
J E Bailey
although it's not clear in the text of this sample, the fact that the first "friend" did not show up is intentional. the operator rest(list) shows all the items of a list except for the head.
Jun 25, 2009
Terence Parr
Yep, note that rest(friends) returns all but first element.
Aug 06, 2009
Patraulea Trandafir
The Python 3 hello world snippet uses the print "blabla" syntax, which is no longer available. It should IMO be changed to print("blabla").
Feb 24, 2011
David Strauss
@Patraulea I've added an (untested) Python 3 sample. I couldn't just modify the Python 2 one because the import is different, and I didn't want to do something confusing like putting the import in a try/except block.
Feb 09, 2012
Linh Tran
I got the error "java.lang.NoClassDefFoundError:antlr/Token" while running your codeimport org.antlr.stringtemplate.;import org.antlr.stringtemplate.language.;
StringTemplatehello=new StringTemplate("Hello, $name$", DefaultTemplateLexer.class);hello.setAttribute("name","World");System.out.println(hello.toString());
I added "stringtemplate-3.2.jar"" in my classpath. Please let me know what I'm missing. Thanks