I’m trying to add values to HashMap in my Freemarker template. I’m also using BeanWrapper so that I can see exposed methods from my Java objects.
In my data model, I have a HashMap:
root.put("myName", new HashMap());
As I mentioned above, Im using BeanWrapper so that I can use all the methods of my Java objects:
BeansWrapper wrapper = new BeansWrapper();
wrapper.setExposureLevel(0);
cfg.setObjectWrapper(wrapper);//cfg = new Configuration();
Now in my template file (test.ftl) I’m trying to invoke put method of HashMap (that I’ve stored in data model..above):
${myName.put["fname:John"]}
This last line does not work, and I’m getting an error:
freemarker.template.TemplateException: Expected hash. myName.put evaluated instead to freemarker.ext.beans.SimpleMethodModel on line 16, column 11 in test.ftl.
Could you tell me, how I can invoke put method of my HashMap in template file?
I suggest you read about Object Wrappers.
I also like this question from the FAQ, from which I will now quote,
If you need the variable in the data model, don’t bother putting it in a map, use the assign directive.
Alas, I understand that the world is not perfect, and sometimes we must do what we can.
If you must, I suggest building an object to wrap your Map, i.e
Then simply put your map wrapper into your model, and you should be able to call put like any other method.