Skip to content

Instantly share code, notes, and snippets.

@smat
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smat/8951420 to your computer and use it in GitHub Desktop.
Save smat/8951420 to your computer and use it in GitHub Desktop.
Render Mustache-templates in Java with Hogan.js
import org.mozilla.javascript.*;
import org.apache.commons.io.IOUtils;
import java.io.*;
public class HoganGenerator {
private StringBuilder parseFile(GeneratorContext context, String file) throws IOException {
StringBuilder javaScriptString = new StringBuilder();
String variableName = String.format("template['%s']", file);
Context cx = Context.enter();
try {
ScriptableObject scope = cx.initStandardObjects();
Reader hoganJs = new InputStreamReader(this.getClass().getResourceAsStream("hogan-2.0.0.js"));
cx.evaluateReader(scope, hoganJs, "hogan.js", 1, null);
Function compile = cx.compileFunction(scope, "function(source) {return Hogan.compile(source, { asString: true })}", "compile_template.js", 1, null);
InputStream templateStream = context.getServletContext().getResourceAsStream(file);
String templateString = IOUtils.toString(templateStream, "UTF-8");
Object template = compile.call(cx, scope, scope, new Object[]{templateString});
return javaScriptString.append(variableName).append(" = ").append(template.toString()).append(";");
}
catch (IOException e) {
throw new RuntimeException(e);
}
finally {
Context.exit();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment