Using StringTemplate with Java

Skip to end of metadata
Go to start of metadata

Installation

All you need to do is get the StringTemplate jar into your CLASSPATH as well as its dependent ANTLR jar. Download the following and put into your favorite lib directory such as /usr/local/lib on UNIX:

Add to your CLASSPATH. On UNIX that looks like

 

 

Java will now see all the libraries necessary to execute ST stuff. Also, check out the latest StringTemplate build. It has both the source and the binary Java jar.

Hello world

Here's a simple, complete program to test your installation.

Hello.java

Here's how to compile and run it from the command line:

Loading template groups

Group files

To load a group file, use the STGroupFile subclass of STGroup:

load file name

This tells StringTemplate to look in the current directory for test.stg. If not found, STGroupFile looks in the CLASSPATH. You can also use a relative path. The following looks for subdirectory templates in the current directory or, if not found, in a directory of the CLASSPATH.

load relative file name

You can also use a fully qualified name:

load fully qualified file name

Group directories

Group files, described above, are like directories of templates packed together into a single file (like text-based jars). To load templates stored within a directory as separate .st files, use STGroupDir instances:

load relative directory of templates

If templates is not found in the current directory, StringTemplate looks in the CLASSPATH. Or, you can specify the exact fully qualified name:

load fully qualified directory of templates

Group strings

For small groups, it sometimes makes sense to use a string within Java code:

URL/URI/Path quagmire

Make sure to pass either a valid file name as a string or a valid URL object. File/dir names are relative like "foo.stg", "foo", "org/foo/templates/main.stg", or "org/foo/templates" OR they are absolute like "/tmp/foo". This is incorrect:

because it yields a file path to a jar and then inside:

file:/somedirectory/AJARFILE.jar!/foo/main.stg

This isn't a valid file system identifier. To use URL stuff, pass in a URL object not a string

See Converting between URLs and Filesystem Paths for more information.

API documentation

Java API

Labels: