Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the ways to update hashmap with FreeMarker?

I started working on ftl FreeMarker recently. I created a hashmap using the #assign.

What is the recommended way to update the values of this hashMap?

Are the data structures(map , list etc) immutable in FreeMarker?

<#assign hashMap1= { "name": "mouse", "price": 50 } >
hashMap1.name = "cat";  // gives error
<#assign hashMap1= hashMap1 + {"name": "cat"} /> // this works fine , but I don't like this approach. it gives false sense of adding keys where we are updating keys.

I tried going through here FreeMarker builtins , but there is no information on this.

like image 232
k1133 Avatar asked Sep 11 '25 05:09

k1133


1 Answers

FTL actually doesn't support modifying data structures. (It's not a generic script language, just a template language.) With hashMap1 = hashMap1 + {"name": "cat"} you aren't updating the existing hash, you are creating a new hash which contains the new key. For that reason I also wouldn't recommend doing it for too many times, as it will get slow (especially the resulting hash).

If you really need to update Map-s from templates, you have to give the template a real Java Map, and use ?api to access Java's Map API.

like image 89
ddekany Avatar answered Sep 13 '25 20:09

ddekany