我目前正在尝试通过nashorn在Java中使用lodash模板引擎,但我遇到了一个问题。
代码如下:
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine nashorn = mgr.getEngineByName("nashorn");
ScriptContext ctx = nashorn.getContext();
Bindings bindings = ctx.getBindings(ScriptContext.ENGINE_SCOPE);
nashorn.eval(readFileToString("externallibs/lodash.min.js"), bindings);
String tpl = readFileToString("hello.tpl");
bindings.put("tpl", tpl);
nashorn.eval("compiled = _.template(tpl);", bindings);
ScriptObjectMirror compiled = (ScriptObjectMirror)nashorn.get("compiled");
System.out.println("compiled = " + compiled);
Map<String, String> props = new HashMap<String, String(1);
props.put("name", "world");
bindings.put("props", props);
System.out.println(compiled.call(this, bindings.get("props"));模板是由Nashorn很好地编译的,如果你查看控制台,你会看到:
compiled = function(obj){obj||(obj={});var __t,__p='';with(obj){__p+='Hello, '+((__t=( name ))==null?'':__t);}return __p}但是,当我尝试调用上面的已编译模板函数时,使用一个map作为参数( props),就像您在JS:tpl.call(this, {name:'world'})中所做的那样。
它会失败,并显示以下错误:
TypeError: Cannot apply "with" to non script object
实际上,我们可以看到该函数的编译版本使用了“with”关键字。
有没有人知道如何解决这个问题?我应该如何发送参数来渲染编译后的模板?
非常感谢你的帮助。
发布于 2015-06-18 11:33:20
您需要将JS脚本对象传递给"with“语句。任意Java对象(不是JS对象--比如java.util.Vector或Foo类的对象)不能用作"with“表达式。您可以使用如下代码创建一个空脚本
Object emptyScriptObj = engine.eval("({})");并将emptyScriptObj传递给您的ScriptObjectMirror.call方法调用。
发布于 2015-06-24 12:28:27
要使用Java map作为"with“语句的作用域表达式,可以使用如下代码:
import javax.script.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws ScriptException {
Map<String, Object> map = new HashMap<>();
map.put("foo", 34);
map.put("bar", "hello");
ScriptEngineManager m = new ScriptEngineManager();
ScriptEngine e = m.getEngineByName("nashorn");
// expose 'map' as a variable
e.put("map", map);
// wrap 'map' as a script object
// __noSuchProperty__ hook is called to look for missing property
// missing property is searched in the map
e.eval("obj = { __noSuchProperty__: function(name) map.get(name) }");
// use that wrapper as scope expression for 'with' statement
// prints 34 and hello from the map
e.eval("with (obj) { print(foo); print(bar); }");
}
}https://stackoverflow.com/questions/30887429
复制相似问题