【问题标题】:Read templates from a file StringTemplate从文件 StringTemplate 中读取模板
【发布时间】:2015-01-17 16:22:46
【问题描述】:

我正在为一些模板使用模板引擎 StringTemplate(显然)。

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

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

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

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

我读过一些关于组文件的东西,但我不太明白,那些是模板文件吗?还是我完全错过了什么?

【问题讨论】:

  • 好吧,你可以做return new String(Files.readAllBytes(Paths.get(templateFile)), StandardCharSets.UTF_8)。例如。但我通常会假设您的模板将位于类路径而不是文件中。
  • @BoristheSpider 问题不是如何读取文件,而是 STringTemplate 引擎中是否有将模板存储在文件中并从文件中读取它们的功能
  • 这里是stringtemplate v3的例子:theantlrguy.atlassian.net/wiki/display/ST/…

标签: java stringtemplate-4


【解决方案1】:

是的,有一些功能可以直接使用,而无需提供您自己的文件加载代码。

来自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 中找到更多信息。
  • 在上面的示例中,模板文件被放置在类路径中。这不是必需的,文件可以放在相对文件夹中,也可以放在绝对文件夹中。

【讨论】:

    猜你喜欢
    • 2012-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 2021-12-17
    相关资源
    最近更新 更多