RichardK RichardK - 11 months ago 140
Javascript Question

Spring MVC, HashMap as model - how to get value using javascript variable as key in jsp

I have a model like this:

public Map<String, String> getAllAvaliableFonts() {

Model is containing font name as a key and css code as a value. Now in jsp I have a javaScript code which should apply css dynamicly to preview font, which looks more/less like this:

var css = '${availableFonts.get("Arial Black")}';

And it's working good with hardcoded map.get(). Css value is taken from HashMap which is model in my jsp.

But I need this map key as a javaScript variable like:

var key = 'Arial Black';
var css = '${availableFonts.get("' + key + '")}';
jQuery('#preview' + i).removeClass().addClass(css);

And it's not working. Is it possible to do it in javaScript ?


There is no way to do it in a way you want since JSP generates on server and JavaScript executes on client. What you can do is to have your model attribute as a JSON, assign it to JavaScript variable when generating a page and then operate with this JavaScript variable. Something like

var myFonts = ${availableFonts};
var myFont = myFonts['some font'];