Reputation: 556
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?
Upvotes: 3
Views: 4004
Reputation: 21
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.
Upvotes: 1
Reputation: 465
I face the same question in Android, i parse the html to String like that :
public static String readInputStreamAsString(InputStream in)
throws IOException {
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while(result != -1) {
byte b = (byte)result;
buf.write(b);
result = bis.read();
buf.flush();
}
return buf.toString();
}
fill the template in data :
Map<String, String> data = new HashMap<>();
data.put("data", "123");
data.put("read_mode","day");
data.put("font_size","small");
Template tmpl = Mustache.compiler().compile(readInputStreamAsString(***InputStream)));
String html = tmpl.execute(data);
It' works fine.
Upvotes: 0
Reputation: 556
String aux = "";
MustacheFactory mf = new DefaultMustacheFactory();
Mustache mustache = mf.compile("path/to/file.html");
StringWriter stringWriter = new StringWriter();
mustache.execute(stringWriter, wrapper);
aux = stringWriter.toString();
System.out.println(aux);
Upvotes: 0
Reputation: 2699
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
.
Upvotes: 1