gpt4 book ai didi

java - 从文件中读取模板 StringTemplate

转载 作者:行者123 更新时间:2023-11-30 08:57:44 33 4
gpt4 key购买 nike

我正在为某些模板使用模板引擎 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/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com