Moon
Moon

Reputation: 22565

How to add a property to a map dynamically in velocity?

I have the following code

$pageName = "test";

$Container = {};

I like to set a property of $Container by a variable. I tried $Container.set("test", $pageName);. It didn't raise any errors, but $Container.test or $Container.get("test"); display nothing.

How do I fix it?

Upvotes: 6

Views: 8913

Answers (2)

Will Glass
Will Glass

Reputation: 4850

The problem is that set is the wrong method. You need to do a put. Remember - Velocity is calling the Java methods. There is no "set" method on a Map object.

Specifically, you can do

$Container.put("test", $pageName)

Now, one weird thing is that this will print "true" or "false" in the page, since the Map.put() method returns a boolean. So I always do

#set($dummy = $Container.put("test", $pageName))

which does the put and stores the result in another reference (which you can then ignore) instead of rendering it to the page.

Upvotes: 15

Chris van Hasselt
Chris van Hasselt

Reputation: 121

Hey I ran into the same problem is the "true" or "false" printed on the page, and there is a simpler way to handle it. What I did is a little weird, and I did it Confluence, which of course uses Velocity under the covers. I mention that because I understand Velocity can be used in may different applications.

With a Confluence user macro, I check for a previously created attribute on the req variable, the request variable, i.e. "myPageVars". Then I use the put method to put a new key-value pair, based on the macro parameters. By using the $! prefix, rather than just $, the output isn't sent to the screen.

... $!req.getAttribute("myPageVars").put( $paramKey, $paramValue ) ...

I'm somewhat new to Velocity, so I can't guarantee this will work in every context, but it seems syntactically easier than the whole #set ($dummy etc. line.

Upvotes: 0

Related Questions