开发者

is mvel suitable for templating JavaScript

开发者 https://www.devze.com 2023-03-05 07:44 出处:网络
We have some JavaScript code templates that we need to interpolate server-side with code like: var version = ${appVersion};

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 int开发者_JS百科erpolation? If so, should I just write my own, or are there any java libs that do simple variable and POJO interpolation?

thanks -nikita


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:

TemplateRuntime.eval(...)

Altering your example above the following works:

String input = "foo()";
assertEquals(input, TemplateRuntime.eval(input, new HashMap()));

The Map passed to the eval method is for variable resolution. e.g.

String input = "foo(@{myVar});";
Map vars = new HashMap();
vars.put("myVar", "bar");
Object eval = TemplateRuntime.eval(input, vars);
assertEquals("foo(bar);", eval);

Take a look through the MVEL language guide and MVEL Templating Introduction for more details.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号