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?
Asked
Active
Viewed 6,194 times
2 Answers
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
-
what is `type` in this ? – Brad Parks Oct 30 '19 at 11:12
-
1just an enum class containing metadata for the template;; ie some have template some dont, with potential template file name – iCodeLikeImDrunk Oct 30 '19 at 13:20
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:

Community
- 1
- 1

But I'm Not A Wrapper Class
- 13,614
- 6
- 43
- 65
-
1
-
Writing to file might reduce the performance of the system. I think StringReader solution is better. – saganas Jun 03 '19 at 09:39