Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 304
Moon Avatar asked May 01 '11 02:05

Moon


1 Answers

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.

like image 177
Will Glass Avatar answered Oct 11 '22 16:10

Will Glass