问题
I have a HashMap in my bean:
HashMap<String, SomeObject> someHashMap;
Then in the velocity template I need to access the HashMap with a value that I have in velocity from other source (in fact I have many keys not only one that's why I need to get the values this way):
$key
How can I access the hashmap with this key? I'm trying:
$someHashMap.get($key)
and
${someHashMap.get($key)}
But those two only write the same thing to the output, meaning that with the first line I literally get:
$someHashMap.get($key)
In the webpage.
Which is the correct way/syntaxis to do this?
Thanks!
回答1:
Both are correct syntax, and they should work.
- Does
$key
have the right value? Print it. - Does
$someHashMap
indeed point to the map? Print it. If not, perhaps you forgot to put in theVelocityContext
being used. - Is the value stored under that key
null
? The default behavior of Velocity is to print out the code that was called when the outcome isnull
. To make it not do that, use the silent notation:$!{someHashMap.get($key)}
回答2:
I had this exact same problem. In my case I tried to do this:
$map.get($locale)
where $locale
is e.g. "fi_FI"
. I solved it by adding quotes inside the brackets:
$map.get("$locale")
I'm not sure, but I think the rationale goes like this:
$map.get( $locale ) -> $map.get( fi_FI ) -> Velocity gets confused
$map.get("$locale") -> $map.get("fi_FI") -> Velocity retrieves correct value
来源:https://stackoverflow.com/questions/21541264/velocity-how-to-retrieve-a-hashmap-value-using-another-velocity-variable