从文件StringTemplate中读取模板

时间:2015-01-17 16:22:46

标签: java stringtemplate-4

我将模板引擎StringTemplate用于某些模板(显然)。

我想要的是能够将我拥有的模板存储在单独的文件中,当然我可以使用简单的.txt文件并将其读入String,看起来有点像这样

ST template = new ST(readTemplateFromFile("template.txt"))

private String readTemplateFromFile(String templateFile){
//read template from file
}

但我想知道的是,StringTemplate引擎中是否有自动执行此操作的功能。因此,我不必编写已经存在的代码。

我已经阅读过有关群组文件的内容,但我不太明白,那些像模板文件一样吗?或者我完全错过了什么?

1 个答案:

答案 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)


一些补充说明:

  • STGroupFileSTGroup的子类。还有其他子类,您可以在JavaDoc
  • 中找到更多相关信息
  • 在上面的示例中,模板文件放在类路径上。这不是必需的,文件也可以放在相对文件夹中或绝对文件夹中。