简体   繁体   中英

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM