Using Java Messages.properties in Javascript

1.4k views Asked by At

I want to use the Java Messages.properties in my Javascript. Currently I am using JSTl to spit out the messages to javascript variable like and use in my 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.

my jsp page

__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. Are there any better approach ?

Thanks.

1

There are 1 answers

1
jfairbank On

I've done something similar in a Grails app, but I have it as a separate build step with Node.js.

Assuming you have the contents of a properties file in a variable contents, you could use something like what I have below. 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.

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