Search code examples
javastringtemplate-4

Read templates from a file StringTemplate


I'm using the template engine StringTemplate for some templates (obviously).

What I want is to be able to store the templates I have in seperate files, ofcourse I can do that with simple .txt files and reading them into a String, looks a bit like this then

ST template = new ST(readTemplateFromFile("template.txt"))

private String readTemplateFromFile(String templateFile){
//read template from file
}

But what I was wondering is if there's functionality in the StringTemplate engine to do that automatically. SO that i don't have to write code that already exists.

I've read something about Group Files but I don't quite understand that,are those like Template files? Or am I completely missing something?


Solution

  • Yes, there is functionality available that can be used directly without providing your own file loading code.

    From the ST JavaDoc:

    To use templates, you create one (usually via STGroup) and then inject attributes using add(java.lang.String, java.lang.Object). To render its attacks, use render().

    To follow that advice the following code can be used.

    First, create a file called exampleTemplate.stg and place it on your classpath.

    templateExample(param) ::= <<
    This is a template with the following param: (<param>)
    >>
    

    Then, render the template by using the following code:

    // Load the file
    final STGroup stGroup = new STGroupFile("exampleTemplate.stg");
    
    // Pick the correct template
    final ST templateExample = stGroup.getInstanceOf("templateExample");
    
    // Pass on values to use when rendering
    templateExample.add("param", "Hello World");
    
    // Render
    final String render = templateExample.render();
    
    // Print
    System.out.println(render);
    

    The output is:

    This is a template with the following param: (Hello World)


    Some additional notes:

    • STGroupFile is a subclass of STGroup. There are other subclasses as well that you find out more about in the JavaDoc.
    • In the example above the template file was placed on the classpath. This is not a requirement, files can be placed in a relative folder or a in an absolute folder as well.