2

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

Nikita
  • 6,019
  • 8
  • 45
  • 54

1 Answers1

1

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.

Bradley Dwyer
  • 8,102
  • 5
  • 32
  • 28
  • The MVEL templating guide link is unavailable, any replacement? – bennyl Sep 06 '15 at 22:56
  • @bennyl: Documentation links updated. I don't think they are exactly the same, but they might suffice. – Bradley Dwyer Sep 09 '15 at 09:20
  • MVEL has a problem with the string like this @{'11412Test'} or @{'Test11412'} it wont be able to parse the above text and throws an error Caused by: [Error: invalid number literal: 11412Test] – – moh Jul 26 '23 at 05:17