9

I have the template saved as a string somewhere and I want to create the mustache with that. How can I do this? Or is it doable?

iCodeLikeImDrunk
  • 17,085
  • 35
  • 108
  • 169

2 Answers2

20

Here is the method I found:

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();
}

So, basically when you just want to render the email from a String template rather than a file, just create the new StringReader with the template.

iCodeLikeImDrunk
  • 17,085
  • 35
  • 108
  • 169
0

If you store that String into a File using FileWriter (or some other classes) and keep the extension .mustache, then you should be able to close and use that file. Here's something I whipped up real quick (it may not work):

//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();

EDIT: I misread the title. You could create a temporary file, then delete it later.

Sources:

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

Community
  • 1
  • 1