Reputation: 118
My problem is really simple, but I think Velocity doesn't support this. I have to access a map or an object with variables names defined within the vm file.
#foreach( $i in [1..10] )
#set( $img_link = "slide${i}_link" )
#set( $img_src = "slide${i}.jpg" )
#set( $img_alt = "slide${i}_alt" )
<li>
<a href="$config.$img_link">
<img src="/assets/images/$img_src" alt="$config.$img_alt" />
</a>
</li>
#end
(config is a Map)
The issue here is that when I send this template to render, I get this code:
<li>
<a href="<toString of map>.slide_1_link">
<img src="/assets/images/slide_1.jpg" alt="<toString of map>.slide_1_alt" />
</a>
</li>
So it looks like at the moment of rendering the template, the $img_src, $img_link and $img_alt are not correctly defined, and velocity tries to render the config object on itself, and at the next round of rendering, config it's already rendered as plain text, and the rest of the variables are just put in there.
One thing more weird than this, is that if I render the vm without config object in the context, and then I add it and render the already rendered content, it's processed correctly, but it doesn't make any sense to me.
The same behaviour I see trying to access a pojo instead of a map.
Do you know if this is a Velocity bug or if I'm missing something?
Thanks.
Java: 1.5 Velocity: 1.7 Velocity-Tools: 2.0
Upvotes: 1
Views: 1069
Reputation: 118
Ok, solved.
There are three different ways to access a map:
If you try using harcoded values, or even variables which values are based on harcoded values, the three ways work perfectly. BUT if you try to access a map using a variable which value is based on another variable, option 2 won't work.
I leave this comment in case someone runs into this same error.
Upvotes: 3
Reputation: 801
I might have misunderstood your question, but it seems to me you are trying to access the map entries in the wrong way. To get the value of a map entry, you should use the #get method:
<li>
<a href="$config.get($img_link)">
<img src="/assets/images/$img_src" alt="$config.get($img_alt)" />
</a>
</li>
This will work provided that there is an entry in the map with the key "slide1_link", one with the key "slide1_alt", one with the key "slide2_link" etc, otherwise an empty string will be output for the not found key.
Upvotes: 0