I'm trying to use mustache to fill an html for me, then i want to get that html and use it as String.
A template like this -> template.xhtml
<table style="width:10%" align="center">
<tr>
<th>Old</th>
<th>New</th>
</tr>
<tr>
<td>{{old}}</td>
<td>{{new}}</td>
</tr>
</table>
With a Hash like this:
HashMap<String, String> scopes = new HashMap<String, String>();
scopes.put("old", "Testing");
scopes.put("new", "Mustache");
Now how do i tell, Mustache to use template.xhtml and fill with scopes and then return me the html?
Take a look at the very bottom of the Mustache project's readme file (https://github.com/spullara/mustache.java#readme). There's an example main method there that does almost exactly what you need. Just use a StringWriter instead of an OutputStreamWriter so that you can get the resulting HTML as a String.
I am using the spring starter mustache.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mustache</artifactId>
<version>2.1.6.RELEASE</version>
</dependency>
MustacheResourceTemplateLoader loader = new MustacheResourceTemplateLoader("emailTemplates/", ".html"); // Inside resources emailTemplates dir
Reader reader = loader.getTemplate("index");
Template tmpl = Mustache.compiler().compile(reader);
// Template String "One, two, {{three}}. Three sir!"
Map<String, String> data = new HashMap<String, String>();
data.put("three", "six");
I hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With