简体   繁体   中英

Velocity template variable name with a special character - a dot

I need to access a value of a Velocity template's variable named:

$myFeature.enabled

Mind the dot within the name. It is defined in the code as:

myFeature.enabled=true

The problem is that, when I want to get the value of that variable withing html context with the following expression:

'${myFeature.enabled}'

it is not resolved and just gives:

"${myFeature.enabled}"

I tried to escape the dot with \\ or change apostrophes to " but without luck.

Changing the name of the variable to a one without a dot is not an easy option for various reasons, so please suggest any other solutions .

The answer is as simple as:

Velocity variable naming : does not allow dots within variable

Also here :

To use a $SINGLE.VARIABLE.IDENTIFIER.WITH.DOTS no backslash is required. The engine will not treat such expression as a variable to be processed because a Velocity variable cannot contain dots according to the Velocity variable notation.

Links:

根据Velocity变量表示法 ,变量不能包含点。

What you can do to work-around the issue, is to add the velocity context itself to the context:

VelocityContext context = new VelocityContext();
context.put("globals", context); // <-- TADA
context.put("myFeature.enabled", Boolean.TRUE);
// ...

then from the template, do:

#if ($globals.get('myFeature.enabled'))
...
#end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM