1

I have a model like this:

 @ModelAttribute("availableFonts")
    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")}';
jQuery('#preview').removeClass().addClass(css);

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 ?

2 Answers 2

1

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'];
Sign up to request clarification or add additional context in comments.

1 Comment

Except that directly passing the map won't make any sense to the JS. It will need to be JSON encoded so that it will be read as an object in the JS.
0

Thank you for help. i've made another workaround - I used map to generate option list with values:

 <form:select path="selectedFont" id ="fonts">
       <c:forEach var="font" items="${availableFonts}">
              <form:option value="${font.value}" label="${font.key}"/>
       </c:forEach>
 </form:select>

And I use jQuery to use values for preview:

 var fontName = jQuery('#fonts>option:selected').text();
 var fontClass = jQuery('#fonts').val();
 jQuery('#preview' + i).removeClass().addClass(fontClass);
 jQuery('#preview' + i).text(fontName);

Preview is just a div:

<div id="preview" />

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.