如何在不使用文件的情况下创建胡子?

时间:2013-06-19 19:01:22

标签: java mustache

我将模板保存为某处的字符串,我想用它创建胡子。我怎样才能做到这一点?还是可行的?

2 个答案:

答案 0 :(得分:13)

以下是我找到的方法:

private String renderMustacheContent() throws IOException {
    MustacheFactory mf = new DefaultMustacheFactory();
    Mustache mustache;

    if (type.getTemplate().trim().isEmpty()) {            
        String emailContent = genCpuEmailContent(cmsKey);
        mustache = mf.compile(new StringReader(emailContent), "cpu.template.email");
    } else {
        mustache = mf.compile(type.getTemplate());
    }

    StringWriter writer = new StringWriter();
    mustache.execute(writer, values).flush();

    return writer.toString();
}

因此,基本上当您只想从String模板而不是文件呈现电子邮件时,只需使用模板创建新的StringReader。

答案 1 :(得分:1)

如果使用FileWriter(或其他一些类)将该String存储到文件中并保留扩展名.mustache,那么您应该能够关闭并使用该文件。这是我快速掀起的东西(可能不起作用):

//write to the file
FileUtils.writeStringToFile(new File("template.mustache"), "example mustache stuff");
//do stuff....
//code for turning template into mustache
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("template.mustache");
mustache.execute(new PrintWriter(System.out), new Example()).flush();
编辑:我误读了标题。您可以创建一个临时文件,然后再删除它。

来源:

How do I save a String to a text file using Java?

https://github.com/spullara/mustache.java/blob/master/example/src/main/java/mustachejava/Example.java

相关问题