Skip to content

Instantly share code, notes, and snippets.

@fancellu
Last active December 30, 2016 21:03
Show Gist options
  • Save fancellu/2127ea2fd8b0dbf846826d71f2954e52 to your computer and use it in GitHub Desktop.
Save fancellu/2127ea2fd8b0dbf846826d71f2954e52 to your computer and use it in GitHub Desktop.
Running JS from JDK1.8 (mustache.js example and raw example with binding)
package nashorn
import javax.script.{Invocable, ScriptEngineManager, SimpleBindings}
import java.io.InputStreamReader
import scala.collection.JavaConverters._
object Mustache {
private val engineManager = new ScriptEngineManager()
val engine = engineManager.getEngineByName("nashorn")
val invocable = engine.asInstanceOf[Invocable]
engine.eval(new InputStreamReader(getClass.getResourceAsStream("mustache.min.js")))
private val mustache = engine.eval("Mustache")
def render(template: AnyRef, jsonObj: AnyRef) = invocable.invokeMethod(mustache, "render", template, jsonObj)
private val JSON = engine.eval("JSON")
def json(jsonString: String) = invocable.invokeMethod(JSON, "parse", jsonString)
}
object MustacheApp extends App {
import Mustache._
val template =
"""Email addresses of {{contact.name}}:
|{{#contact.emails}}
|- {{.}}
|{{/contact.emails}}""".stripMargin
val contactJson =
"""{
"contact": {
"name": "Mr A", "emails": ["[email protected]", "[email protected]"]
}
}"""
val jsonObj = json(contactJson)
println(render(template, jsonObj))
// using play Json to create json blob here, same as commented out code
import play.api.libs.json._
val contactJson2=Json.obj("contact" -> Json.obj("name"-> "Mr B", "emails" ->List("[email protected]", "[email protected]") ))
// val contactJson2 =
// """{
// "contact": {
// "name": "Mr B", "emails": ["[email protected]", "[email protected]"]
// }
// }"""
println(render(template, json(contactJson2.toString)))
// if mustache isn't enough, you can always use raw Javascript
val map=scala.collection.mutable.Map[String,Object]("greeting"->"Hello", "json"->json(contactJson2.toString))
val bindings=new SimpleBindings(map.asJava)
private val custom = engine.eval(
"""
|var date=new Date
|greeting+' '+json.contact.name+', it is now '+date;
""".stripMargin, bindings)
println(custom)
}
Email addresses of Mr A:
- [email protected]
- [email protected]
Email addresses of Mr B:
- [email protected]
- [email protected]
Hello Mr B, it is now Fri Dec 30 2016 20:50:52 GMT+0000 (GMT)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment