I have a java Map<Country, List<Expr>> countryToExprMap
in the backend service.
In my web page rendered by Thymeleaf, I have a Country
drop down to select Country, and a Expr
drop down, where I only want Expr
s mapped by the selected Country
to be displayed.
To do that, I need to pass countryToExprMap
from Java to Javascript so that I can know the eligible Expr
s from a given Country
, so as to build a updateExprOptions
function to be called by the Country
dropdown on "change" event. Something like:
var exprDropDown = document.getElementById("exprs");
// Map from Java
var exprs = countryToExprMap[selectedCountry];
// Create options for the expr dropdown
for (var i = 0; i < exprs.length; i++) {
var option = document.createElement("option");
option.value = exprs[i];
option.text = exprs[i];
exprDropDown.appendChild(option);
}
Unfortunately it doesn’t look like there’s a way to pass the map variable from Java to JavaScript. Any advice appreciated.
What I can think of is to stringify the map in Java,
set it as data-* attribute to a html element using Thymeleaf,
and at last deserialise the map in JavaScript to use it there.
2
Answers
Thanks to @Metroids.
I was able to use Thymeleaf native way to solve it:
Something like this (change ObjectMapper to any JSON stringifier you have)
If the JSON is not in the JSP, but can be delivered by your backend ass a file, then it is simpler: