2

I have a code like this on my JavaScript file x.js

alert("<spring:message code='plants.selectedPlant.name' javaScriptEscape='true' />");

In a file messages.properties I have the line:

plants.selectedPlant.name = Roses

But it just alerts the text <spring:message code='plants.selectedPlant.name' javaScriptEscape='true' /> but not the value.

I'm not importing anything on my JS file.

AlBlue
  • 23,254
  • 14
  • 71
  • 91
user3444431
  • 49
  • 2
  • 9
  • JS files are not usually "rendered" as GSP files (unless you are using a plugin or wiring them manually). So the GSP syntax will not work. You can put that code inside a ` – nickdos Mar 26 '14 at 08:57
  • 1
    The GSParse plugin might help http://grails.org/plugin/gsp-arse – nickdos Mar 26 '14 at 09:01
  • possible duplicate of [Resolving spring:messages in javascript for i18n internationalization](http://stackoverflow.com/questions/6218970/resolving-springmessages-in-javascript-for-i18n-internationalization) – Pedro Affonso Jul 08 '15 at 13:58

2 Answers2

2

One useful trick is to do something like this:

HTML

<span id="selectedPlantName" display="none">
    <spring:message code='plants.selectedPlant.name' javaScriptEscape='true' />
</span>

JS (Assuming you use jQuery)

alert($("#selectedPlantName").text());

Or

take a look at the accepted answer in this question:

Resolving spring:messages in javascript for i18n internationalization

Community
  • 1
  • 1
Pedro Affonso
  • 1,656
  • 15
  • 26
0

The answer provided by Pedro works fine (and I upvoted it), but in my opinion this is not the cleanest solution because you define a span with id, display etc. just to access the value later. Imagine having 20 messages - this will be a lot of unnecessary code. I would keep it simple and use plain JavaScript:

var myText = ""
if(locale === "de") {
  myText = "<German Text>"
} else{
  myText = "<English text>"
}
bdskfsdk321dsad3
  • 113
  • 1
  • 2
  • 9