gpt4 book ai didi

java - Lodash 模板引擎 Nashorn

转载 作者:行者123 更新时间:2023-11-30 06:14:05 27 4
gpt4 key购买 nike

我目前正在尝试使用 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}

但是当我尝试使用映射作为参数( Prop )调用上面编译的模板函数时,就像在 JS 中所做的那样:
tpl.call(this, {name:'world'})

失败并出现以下错误:


类型错误:无法将“with”应用于非脚本对象

事实上,我们可以看到函数的编译版本使用了“with”关键字。

有没有人知道如何解决这个问题?我应该如何发送参数来渲染编译后的模板?

非常感谢您的帮助。

最佳答案

您需要将一个 JS 脚本对象传递给“with”语句。任意 Java 对象(不是 JS 对象——比如 java.util.Vector 或类 Foo 的对象)不能用作“with”表达式。您可以使用如下代码创建一个空脚本

Object emptyScriptObj = engine.eval("({})");

并将 emptyScriptObj 传递给您的 ScriptObjectMirror.call 方法调用。

关于java - Lodash 模板引擎 Nashorn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30887429/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com