Sriharsha Sistalam
Project manager at D.E.Shaw India. Interested in front end, distributed systems, micro services.
using all your kick-ass client side Javascript templating frameworks in Java
by Sriharsha Sistalam (@harry_sistalam)
If you are using #nodejs, you are good to go. Else?
So do I need another templating library for Java?
Choose a template which has support for the language you need
and hope that they have a "Jar" for you!
Problem with using dependency tools (mvn, npm)?
At you fingertips you have access to thousands of libraries to use. Just add in package.json/pom.xml
Dependency hell!
Side note: Please please don't use '*' in your package.json
Java has a "JavaScript" engine (Yay!)
Rhino in JS < 8 , Nashorn in Java 8 with ES standard (seriously? ES6?)
It has been used for ages to use evaluate Dynamic Expressions in Java.
//script.js
var fun1 = function(name) {
return ('Hello World, ' + name);
};
var fun2 = function (object) {
print("JS Class Definition: " + Object.prototype.toString.call(object));
};
// main Java code.
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("nashorn");
engine.eval(new FileReader("script.js"));
Invocable invocable = (Invocable) engine;
Object result = invocable.invokeFunction("fun1", "JSFoo");
System.out.println(result);
//output
=> Hellow World, JSFoo
Nashron gives the full ability to load various files, templates, libraries into context
ScriptEngineManager engineManager = new ScriptEngineManager();
ScriptEngine engine = engineManager.getEngineByName("nashorn");
File file = new File("dust-full.js");
System.out.println("File content is " + file)
engine.eval(new FileReader(file));
// Get the dust js object
Invocable invocable = (Invocable) engine;
Object dustjs = engine.eval("dust");
// Just a string based template
String template = "Hello {name}! You have {count} new messages.";
Object compileTemplate = invocable.invokeMethod(dustjs, "compile",
template, "myphrase");
Object loadedSource = invocable.invokeMethod(dustjs, "loadSource",
compileTemplate);
Text
Writer writer = new StringWriter();
String nameJson = "{\"name\": \"Mick\",\"count\": 30}";
/**
* Create the JSON Object based on the user model
*/
Bindings bindings = new SimpleBindings();
bindings.put("name", "myphrase");
bindings.put("json", nameJson);
bindings.put("writer", writer);
/**
* Set the context to evalutate the bindings.
*/
engine.getContext().setBindings(bindings, ScriptContext.GLOBAL_SCOPE);
/**
* Evaluate the bindings. i.e build HTML
*/
engine.eval(renderScript, engine.getContext());
System.out.println(writer);
How do you generate the data for Templates.
Client side: We use JSON.
Server side: We have Models (Pojo)
Convert your POJO objects to JSON representation using a JSON generator like GSON.
By Sriharsha Sistalam
A flash talk on using client side templates on Java.
Project manager at D.E.Shaw India. Interested in front end, distributed systems, micro services.