8

When we try to display a label from a properties file, using spring tags, we can write:

<spring:message javaScriptEscape="true" code="label" />

i am not able to find out what is the use of javaScriptEscape="true". Why do we need this?

Victor
  • 16,609
  • 71
  • 229
  • 409

1 Answers1

14

If the message is a JavaScript string literal, such as in

<script>
    function sayI18nedHello() {
        alert('<spring:message javaScriptEscape="true" code="hello" />');
    }
</script>

Then you need this attribute, which will escape the single and double quotes, the newline chars, the tabs, etc. in order to make sure that the generated JavaScript is valid.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Thank you so much. Can you please tell me whe n I should use htmlEscape and when I use javascriptEscape? – Victor Mar 25 '13 at 19:06
  • 5
    Well, htmlEscape when the message is included in an HTML document, and javascriptEscape when it's included in a JavaScript string literal. – JB Nizet Mar 25 '13 at 19:08
  • Where is the actual documentation for that? The Spring website / docs themselves just note that it does “Set JavaScript escaping for this tag”, but not whether it requires surrounding quotes, and which ones, if any. I’d have expected it to _provide_ the quotes, so that you can just say alert(); and it would do the rest. – mirabilos Sep 17 '13 at 08:08
  • If javaScriptEscape provided the quotes, then it wouldn't be what programmers normally call escaping, which is changing the characters you want in the string into their escape sequences that you can put in the string literal. In C-based languages this usually means sticking backslashes in front of things. But you're absolutely right to call out the lousy Spring documentation; many people in the audience aren't going to know any of that and absolutely need to hear it so they have the best chance of not creating templates that are horrible garbage. – rakslice Jun 14 '14 at 03:14
  • Is Spring the best tool for this job though? see http://stackoverflow.com/questions/25491391/springescapebody-results-in-invalid-json and also http://stackoverflow.com/questions/7539954/java-json-serialization-best-practice – Adriano Sep 23 '14 at 11:17