Search code examples
javamustache

How to create a mustache without using a file?


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?


Solution

  • 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.