menu

Questions & Answers

Thymeleaf: access map with variable key

This is my model.

Map <String, String>

e.g.

{ sam: "NY", tom: "SF", sue: "WN" }

How can I access the value from JavaScript if I have the key in a variable?

// mod is the model
    
var key = "sam";
var foo = [[${mod.get ("sam")}]];    // key by string -> foo is defined (OK)
var bar = [[${mod.get (key)}]];      // key by variable -> bar is undefined
Answers(1) :

You can pass the full Java map to your JavaScript code in your Thymeleaf template:

<script th:inline="javascript">
    var key = "sam";
    var mymap = [[${mod}]];
    var bar = mymap[key];
    console.log( bar );
</script>

Thymeleaf will create the following JavaScript (as seen in your rendered web page):

var key = "sam";
var mymap = {"sue":"WN","tom":"SF","sam":"NY"};
var bar = mymap[key];
console.log( bar ); // this prints "NY" to the browser console

The key point here is: Thymeleaf only exists on the server - it cannot execute JavaScript commands (on the server) - and there is no variable called key in your model that you pass to Thymeleaf.

Therefore the key in the Thymeleaf expression ${mod.get (key)} is null.


Another way around this is to add "sam" to the model in your Java code - for example:

model.put("key", "sam");

Or, for Spring:

model.addAttribute("key", "sam");

Now, there is a valid value for key, which can be used to evaluate the Thymeleaf expression ${mod.get (key)} on the server.

But this does not use the JavaScript line var key = "sam";.

This option may not be possible - it depends on where the value "sam" originates. If it's not available to your Java code, this is obviously not going to help you.


Reference: See Advanced inlined evaluation and JavaScript serialization for more details.