[英]Access messages.properties value from javascript
I have a code like this on my JavaScript file x.js
我的 JavaScript 文件x.js
上有这样的代码
alert("<spring:message code='plants.selectedPlant.name' javaScriptEscape='true' />");
In a file messages.properties
I have the line:在文件messages.properties
我有一行:
plants.selectedPlant.name = Roses
But it just alerts the text <spring:message code='plants.selectedPlant.name' javaScriptEscape='true' />
but not the value.但它只是提醒文本<spring:message code='plants.selectedPlant.name' javaScriptEscape='true' />
而不是值。
I'm not importing anything on my JS file.我没有在我的 JS 文件中导入任何东西。
One useful trick is to do something like this:一个有用的技巧是做这样的事情:
HTML HTML
<span id="selectedPlantName" display="none">
<spring:message code='plants.selectedPlant.name' javaScriptEscape='true' />
</span>
JS (Assuming you use jQuery) JS(假设您使用 jQuery)
alert($("#selectedPlantName").text());
Or或者
take a look at the accepted answer in this question:看看这个问题中接受的答案:
Resolving spring:messages in javascript for i18n internationalization 解决 spring:i18n 国际化的 javascript 中的消息
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. Pedro 提供的答案工作正常(我赞成),但在我看来,这不是最干净的解决方案,因为您定义了一个带有 id、display 等的跨度,只是为了稍后访问该值。 Imagine having 20 messages - this will be a lot of unnecessary code.想象一下有 20 条消息 - 这将是很多不必要的代码。 I would keep it simple and use plain JavaScript:我会保持简单并使用纯 JavaScript:
var myText = ""
if(locale === "de") {
myText = "<German Text>"
} else{
myText = "<English text>"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.