我将模板引擎StringTemplate用于某些模板(显然)。
我想要的是能够将我拥有的模板存储在单独的文件中,当然我可以使用简单的.txt文件并将其读入String
,看起来有点像这样
ST template = new ST(readTemplateFromFile("template.txt"))
private String readTemplateFromFile(String templateFile){
//read template from file
}
但我想知道的是,StringTemplate引擎中是否有自动执行此操作的功能。因此,我不必编写已经存在的代码。
我已经阅读过有关群组文件的内容,但我不太明白,那些像模板文件一样吗?或者我完全错过了什么?
答案 0 :(得分:2)
是的,有可用的功能可以直接使用而无需提供您自己的文件加载代码。
来自ST JavaDoc:
要使用模板,您可以创建一个模板(通常通过STGroup),然后使用add(java.lang.String, java.lang.Object)注入属性。要进行攻击,请使用render()。
要遵循该建议,可以使用以下代码。
首先,创建一个名为exampleTemplate.stg
的文件并将其放在类路径上。
templateExample(param) ::= <<
This is a template with the following param: (<param>)
>>
然后,使用以下代码渲染模板:
// 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);
输出结果为:
这是一个包含以下参数的模板:( Hello World)
一些补充说明:
STGroupFile
是STGroup
的子类。还有其他子类,您可以在JavaDoc。