user3444431
user3444431

Reputation: 49

Access messages.properties value from javascript

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.

Upvotes: 2

Views: 4593

Answers (2)

bdskfsdk321dsad3
bdskfsdk321dsad3

Reputation: 143

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>"
}

Upvotes: 0

Pedro Affonso
Pedro Affonso

Reputation: 1676

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

Upvotes: 2

Related Questions