我正在使用模板引擎 StringTemplate 来处理某些模板(显然)。
我想要的是能够将我拥有的模板存储在单独的文件中,当然我可以使用简单的 .txt 文件并将它们读入 String
中,看起来有点像这样
ST template = new ST(readTemplateFromFile("template.txt"))
private String readTemplateFromFile(String templateFile){
//read template from file
}
但我想知道 StringTemplate 引擎中是否有功能可以自动执行此操作。这样我就不必编写已经存在的代码。
我读过一些有关组文件的内容,但我不太明白,那些是不是类似于模板文件?或者我完全错过了什么?
最佳答案
是的,有一些功能可以直接使用,而无需提供您自己的文件加载代码。
来自ST JavaDoc :
To use templates, you create one (usually via STGroup) and then inject attributes using add(java.lang.String, java.lang.Object). To render its attacks, use 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);
输出为:
This is a template with the following param: (Hello World)
一些附加说明:
STGroupFile
是STGroup
的子类。还有其他子类,您可以在 JavaDoc 中找到更多信息。 .- 在上面的示例中,模板文件放置在类路径中。这不是必需的,文件可以放置在相对文件夹中,也可以放置在绝对文件夹中。
关于java - 从文件 StringTemplate 中读取模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28001536/