Elias Dorneles
Elias Dorneles

Reputation: 23796

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?

Upvotes: 4

Views: 3765

Answers (2)

user166390
user166390

Reputation:

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.

Upvotes: 5

PhiLho
PhiLho

Reputation: 41132

Very interesting trick above (by pst), which also gives a hint: "not valid group template syntax".

So, for reference, here is an alternative to his code, using a valid syntax for such group:

 STGroup groupS = new STGroupString("some group", "val(value) ::= \"<span>Value is {value; format=\\\"%1.5f\\\"}</span>\"", '{', '}');
 groupS.registerRenderer(Number.class, new NumberRenderer());
 ST valTpl = groupS.getInstanceOf("val");
 valTpl.add("value", 3.14159265358979353);
 System.out.println(valTpl.render());

The syntax becomes unwieldy within Java strings, with the many escapes...

Upvotes: 1

Related Questions