Search code examples
javastringtemplatestringtemplate-4

How to get StringTemplate V4 to ignore < as delimiter?


I'm using StringTemplate V4 to generate some HTML code in my project. I need to have HTML formatting in my templates, so using the default delimiters < and > would be very awkward.

So, I'm creating a group passing the delimiter as argument (as recommended by this question), but it simply doesn't work.

Here is my test code:

public void testTemplate() {
    char sep = '$';
    STGroup stGroup = new STGroupString("temp",
            "<html>hello, $name$!</html>", sep, sep);
    System.out.println("Group created");
    ST st = stGroup.getInstanceOf("temp");
    if (st == null) {
        System.out.println("Failed to get template!");
    } else {
        st.add("name", "Guest");
        System.out.println("Template initialized correctly");
    }
}

And this is the output that I get:

temp 1:1: invalid character '<'
temp 1:5: invalid character '>'
temp 1:1: garbled template definition starting at 'html'
temp 1:6: garbled template definition starting at 'hello'
temp 1:13: invalid character '$'
temp 1:18: invalid character '$'
temp 1:19: invalid character '!'
temp 1:21: invalid character '<'
temp 1:22: invalid character '/'
temp 1:14: garbled template definition starting at 'name'
temp 1:26: invalid character '>'
temp 1:22: garbled template definition starting at 'html'
Failed to get template!

What am I missing here?


Solution

  • The issue is the the template supplied to the STGroupString constructor is not valid "group template" syntax.

    To get a Group Template that doesn't require the special syntax try:

    STGroup group = new STGroup('$', '$');
    group.registerRenderer(...);
    CompiledST compiledTemplate = group.defineTemplate("name", ...);
    compiledTemplate.hasFormalArgs = false; // very important!
    
    // later on...
    ST template = group.getInstanceOf("name");
    

    (This above is an adaptation of my C# code so YMMV. I have tried to ensure the types/names are valid and the syntax is correct, but have not verified it. Feel free to update/correct as required.)

    Happy coding.