Java 从StringTemplate文件中读取模板
我将模板引擎StringTemplate用于一些模板(显然) 我想要的是能够将我拥有的模板存储在单独的文件中,当然,我可以用简单的.txt文件将它们读入Java 从StringTemplate文件中读取模板,java,stringtemplate-4,Java,Stringtemplate 4,我将模板引擎StringTemplate用于一些模板(显然) 我想要的是能够将我拥有的模板存储在单独的文件中,当然,我可以用简单的.txt文件将它们读入字符串中,看起来有点像这样 ST template = new ST(readTemplateFromFile("template.txt")) private String readTemplateFromFile(String templateFile){ //read template from file } 但我想知道的是,Strin
字符串中,看起来有点像这样
ST template = new ST(readTemplateFromFile("template.txt"))
private String readTemplateFromFile(String templateFile){
//read template from file
}
但我想知道的是,StringTemplate引擎中是否有自动执行该操作的功能。这样我就不必编写已经存在的代码
我读过一些关于组文件的内容,但我不太明白,这些文件像模板文件吗?还是我完全遗漏了什么?是的,有一些功能可以直接使用,而无需提供您自己的文件加载代码
从:
要使用模板,请创建一个模板(通常通过),然后使用注入属性。要呈现其攻击,请使用
要遵循该建议,可以使用以下代码
首先,创建一个名为exampleTemplate.stg
的文件,并将其放在类路径上
templateExample(param) ::= <<
This is a template with the following param: (<param>)
>>
输出为:
这是一个具有以下参数的模板:(Hello World)
一些补充说明:
STGroupFile
是STGroup
的子类。还有其他子类,您可以在中了解更多
- 在上面的示例中,模板文件被放置在类路径上。这不是要求,文件可以放在相对文件夹中,也可以放在绝对文件夹中
好的,您可以执行返回新字符串(Files.readAllBytes(path.get(templateFile)),StandardCharSets.UTF_8)
。例如但我通常会假设您的模板位于类路径上,而不是文件中。@BoristSpider问题不在于如何读取文件,而是STringTemplate引擎中是否有将模板存储在文件中并从文件中读取的功能。STringTemplate v3
:
// 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);