embed java code inside a template

可紊 提交于 2019-12-06 23:42:34

No, java code embedding into a Template is not intended / not provided. That makes it easier to prevent a mess / mixture of view and model/logic.

In Your case, You can easily put the calculated things into java property getter function, which can be referenced and evaluated by StringTemplate as a kind of bean property.

e.g.

Put in Your template group file MyTemplate.stg:

myTemplate(f) ::= <<
...
Blabla  <f.message>  blabla
...
>>

Put in Your Java source code:

class MyClass() {
  ...
  private String internal_message;
  public getMessage() { 
    return internal_message; 
  }
  ...
}

Invoke the template:

STGroupFile stg = new STGroupFile("MyTemplate.stg");
ST templ = stg.getInstanceOf("myTemplate");
templ.add("f", new MyClass());

With this, the template logic <f.message> invokes getMessage() of Your java object instance f.

Andy Stabler

As @Hartmut said, no you can't embed java code inside a template, but you can create a custom StringRenderer that you could use to format the strings in the way you want.

You could then pass your custom format string to the renderer like this:

test(description) ::= <<
    this is original <description>
    this is caps <description; format="upper">
    this is custom format <description; format="my-format-string">
>>

P.S if you're just interested in changing the text case you might not need to roll your own, just add a reference to the StringRenderer that comes bundled with StringTemplate using:

templateGroup.registerRenderer(String.class, new StringRenderer());

and pass "upper", "lower", or "cap" as the format string

See my answer here for more info

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