java - 从文件 StringTemplate 中读取模板

标签 java stringtemplate-4

我正在使用模板引擎 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)


一些附加说明:

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

关于java - 从文件 StringTemplate 中读取模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28001536/

相关文章:

java - 如何遍历stringtemplate中的Java列表?

java - 我只想给出一个参数而不是全部 4 个

java - 如何在javamail中设置正确的电子邮件地址?

java - 企业应用集成: Ways to communicate show rooms with central office

java - 使用 Java 连接 AWS aerospike 实例

java - 在java jxl api中使用excel公式结果

antlr4 - 使用 Antlr 4 和 stringtemplate 4 将 PL/SQL 代码转换为 Java

java - StringTemplate 没有找到 getter