Velocity, how to retrieve a hashmap value using another velocity variable

余生长醉 提交于 2020-01-04 05:57:15

问题


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 the VelocityContext 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 is null. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!