mvel 适合模板化 JavaScript
我们有一些 JavaScript 代码模板,需要在服务器端插入如下代码:
var version = ${appVersion};
我认为 MVEL 适合于此,但它似乎太聪明了:
String input = "foo()";
assertEquals(input, MVEL.evalToString(input));
barfs 具有:
[错误:没有这样的方法或函数: foo] [附近:{... foo( ....}] ^ [行:1,列:0] 在 org.mvel2.PropertyAccessor.getMethod(PropertyAccessor.java:843) 在 org.mvel2.PropertyAccessor.getNormal(PropertyAccessor.java:203)
对于简单的 var 插值来说 MVEL 是否过度?如果是这样,我应该自己编写,还是有任何 java 库可以执行简单变量和 POJO 插值?
谢谢 -尼基塔
We have some JavaScript code templates that we need to interpolate server-side with code like:
var version = ${appVersion};
I thought MVEL would be suitable to this, but it appears to be too smart:
String input = "foo()";
assertEquals(input, MVEL.evalToString(input));
barfs with:
[Error: no such method or function:
foo] [Near : {... foo( ....}]
^ [Line: 1, Column: 0] at
org.mvel2.PropertyAccessor.getMethod(PropertyAccessor.java:843)
at
org.mvel2.PropertyAccessor.getNormal(PropertyAccessor.java:203)
is MVEL overkill for simple var interpolation? If so, should I just write my own, or are there any java libs that do simple variable and POJO interpolation?
thanks
-nikita
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于这种类型的模板使用 MVEL 是完全可以的。
问题是您正在 MVEL 类上执行方法。此类上的方法旨在评估和编译 MVEL 表达式,而不是模板。
您实际上想要的是以下内容:
更改上面的示例可以实现以下效果:
传递给 eval 方法的 Map 用于变量解析。例如,
查看MVEL 语言指南和MVEL 模板简介 了解更多详细信息。
It's perfectly fine to use MVEL for this type of templating.
The problem is you're executing methods on the MVEL class. The methods on this class are designed to evaluate and compile MVEL expressions, not templates.
What you're actually after is the following:
Altering your example above the following works:
The Map passed to the eval method is for variable resolution. e.g.
Take a look through the MVEL language guide and MVEL Templating Introduction for more details.