简体   繁体   English

从javascript访问messages.properties值

[英]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.

相关问题 如何使用 javascript 中的 thymeleaf 访问 messages.properties,但使用 javascript 中定义的变量 - How to access messages.properties with thymeleaf from javascript, but using variables defined in javascript 在Javascript中使用Java Messages.properties - Using Java Messages.properties in Javascript Grails从外部JavaScript文件中的messages.properties设置错误消息 - Grails Set Error Message From messages.properties In External JavaScript File Thymeleaf 使用来自 messages.properties 文件的动态值构造 URL - Thymeleaf construct URL with dynamic values from messages.properties file 我可以从 JavaScript 访问无效/自定义 CSS 属性的值吗? - Can I access the value of invalid/custom CSS properties from JavaScript? 从 class 方法访问 javascript 中的 class 属性 - Access class properties in javascript from class method Javascript从子方法访问父属性 - Javascript Access to parent properties from child method 是否可以从javascript访问as3自定义属性? - Is it possible to access as3 custom properties from javascript? 如何从Javascript对象访问属性? - How to access properties from a Javascript object? 如何在javascript中从IFFE访问私有属性 - How to access private properties from an IFFE in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM