Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

While reading this section you may wish to consult the StringTemplate API javadocs, or the annotated version here: XXX ST condensed -- API annotated which highlights the most-needed methods.

...

Single template from string

Code

Result

No Format

StringTemplate st = new StringTemplate("Hello, $name$");
st.setAttribute("name", "World");
String s = st.toString();

Hello, World

...

Use an alternative expression delimiter

Code Block

StringTemplate st = new StringTemplate("Hello, <name>", AngleBracketTemplateLexer.class);

Single template from string, and use an instance

Code

Result

No Format

StringTemplate st = new StringTemplate("Hello, $name$");
StringTemplate sti = st.getInstanceOf();
sti.setAttribute("name", "World");
String s = sti.toString();

Hello, World

... and st can be used to create more fresh instances

...

Simple template with multi-valued attribute

Code

Result

No Format

String tmpl = "Hello, $arg;separator=\", \"$";
StringTemplate st = new StringTemplate(tmpl);
st.setAttribute("arg", "One");
st.setAttribute("arg", "Two");
String s = st.toString();

Hello, One, Two

...

Insantiate and use a template from a group of files in a template group directory

No Format

StringTemplateGroup stg = new StringTemplateGroup("mygroup", "/somepath/mygroupdir");
StringTemplate st = stg.getInstanceOf("mytemplate");
st.setAttribute("arg1","Value1");
String s = st.toString();

/somepath/mygroupdir/mytemplate.st:

No Format

Hello, $arg1$

Result: Hello, Value1

...

Adding a named template from a string

No Format

...
tmptext = "Hello, $name$";
newst = stg.defineTemplate("mynewtmp", tmptext);
...

...

Group directories with inheritance

No Format

StringTemplateGroup mysuper = new StringTemplateGroup("mysupergrp", "/somepath/master");
StringTemplateGroup mysub = new StringTemplateGroup("mysubgrp" , "/somepath/sub");
mysub.setSuperGroup(mysuper);
....

...

Examples: Template-group-file mode

Single stg file

No Format

StringTemplateGroup stg = new StringTemplateGroup( new FileReader("/somepath/mygroup.stg") );
StringTemplate st = stg.getInstanceOf("sometmp");
st.setAttribute("arg1","Value1");
String s = st.toString();

...

With supergroup file

No Format

StringTemplateGroup stgsuper = new StringTemplateGroup( new FileReader("/somepath/mysuper.stg") );
StringTemplateGroup stg = new StringTemplateGroup( new FileReader("/somepath/mygroup.stg") );
StringTemplate st = stg.getInstanceOf("sometmp");
st.setAttribute("arg1","Value1");
String s = st.toString();

/somepath/mygroup.stg:

No Format

group mygroup: mysuper; // inherit from mysuper

sometmp(arg1) ::= <<
Here is arg1: <arg1>
>>

...