Last active
August 29, 2015 13:56
-
-
Save smat/8951420 to your computer and use it in GitHub Desktop.
Render Mustache-templates in Java with Hogan.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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