How to get StringTemplate V4 to ignore < as delimiter?

☆樱花仙子☆ 提交于 2019-12-12 11:32:12

问题


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?


回答1:


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.




回答2:


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...



来源:https://stackoverflow.com/questions/11146113/how-to-get-stringtemplate-v4-to-ignore-as-delimiter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!