简体   繁体   English

在Javascript中使用Java Messages.properties

[英]Using Java Messages.properties in Javascript

I want to use the Java Messages.properties in my Javascript. 我想在我的Javascript中使用Java Messages.properties。 Currently I am using JSTl to spit out the messages to javascript variable like and use in my js. 目前,我正在使用JSTl将消息吐出到javascript变量中,并在js中使用。 Is there a better approach. 有没有更好的方法。 I looked at jawr plugin Javascript i18n message generator, but didnt quite understand other than adding it servlet reference to web.xml file. 我看了下颚插件 Javascript i18n消息生成器,但是除了将servlet引用添加到web.xml文件之外,还不太了解。

my jsp page 我的jsp页面

__messages = {
            errorPattern: '<fmt:message key="errors.match_pattern" />',
            notBothBeSet: '<fmt:message key="errors.not_both_be_set"/>'
}

My requirement is just to use java properties in js, wiring using JSTL sounds off. 我的要求是仅在js中使用java属性,使用JSTL进行连线听起来很困难。 Are there any better approach ? 有没有更好的方法?

Thanks. 谢谢。

I've done something similar in a Grails app, but I have it as a separate build step with Node.js. 我已经在Grails应用程序中做了类似的事情,但是我将它作为Node.js的单独构建步骤。

Assuming you have the contents of a properties file in a variable contents , you could use something like what I have below. 假设您在可变内容中具有属性文件的contents ,则可以使用类似下面的内容。 It could probably be more flexible on input, but it works. 输入可能会更灵活,但是可以。 This assumes you don't put spaces around your = in your properties file. 假设您没有在属性文件中的=周围放置空格。 The function returns JSON, so you would want to write the return value to a JS file. 该函数返回JSON,因此您需要将返回值写入JS文件。

function getMessages(contents) {
  var splitter = /^(.*?)=(.*)$/;

  var data = contents.trim().split('\n').reduce(function(memo, line) {
    var split = line.match(splitter);

    if (split) {
      memo[split[1]] = split[2];
    }

    return memo;
  }, {});

  return JSON.stringify(data, null, '  ');
}

getMessages('test=hello\nfoo=bar');
// {
//  "test": "hello",
//  "foo": "bar"
// }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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