javastringtemplate-4

StringTemplates, how to create a group of templates in code


I'm new to StringTemplates and try to figure out how to build a group of templates from a source other than files (it's actually in a database).

I miss something like (pseudocode):

STGroup group = new STGroup();
group.addTemplate("name", args, "... <actual template goes here> ...");

I wasn't able to find anything similar. STGroup.defineTemplate-methods all look like for internal use only or are java-doc'ed "for testing". STGroup.compile takes a Token.

I actually want to write the contents of a group file in Java. STGroupString doesn't look promising performance-wise. We have hundreds of templates, some of them very large. It doesn't make sense to me to render it into group file syntax and then let StringTemplates parse that back to a name, args, contents structure instead of directly passing in that structure.


Solution

  • You can use STGroup.defineTemplate(), even if its Javadoc says for testing:

    STGroup stGroup = new STGroup();
    
    stGroup.defineTemplate("myTemplate", "is this true? <if (true)>yes<endif>");
    
    // will print "is this true? yes"
    System.out.println(stGroup.getInstanceOf("myTemplate").render());