DraganS
DraganS

Reputation: 2699

Grails: Reading the Resource Bundle

I tried to get list of message/translations from resource bundle but it fails (throws exception). The app is running on Tomcat from IDEA:

Locale locale = new Locale("en");
ResourceBundle bundle = ResourceBundle.getBundle('i18n/dictionary', locale);

What is wrong here. i18n/dictionary is on class path. Could be 'i18n/dictionary' is wrong.

I'm able to get message source, but I can't get keys from this (SPRING) object:

def messageSource = grailsAttributes.getApplicationContext().getBean("messageSource");

Upvotes: 4

Views: 1692

Answers (2)

Lyra20
Lyra20

Reputation: 11

this works for me.

ResourceBundle resourceBundle = ResourceBundle.getBundle("grails-app.i18n.messages", locale)

Upvotes: 1

DraganS
DraganS

Reputation: 2699

The resource path was incomplete. If you need the translation table on the front-end, maybe the following controller could be useful:

class ClientMessagesController {

def index = {
    Locale locale = session.getAttribute('locale') ?: new Locale("en");
    ResourceBundle bundle = ResourceBundle.getBundle('\\grails-app\\i18n\\clientMessages', locale);

    def sep = '';
    def sb = new StringBuilder();
    sb.append('<script type="text/javascript">\n');
    sb.append('_i18n = {\n');
    bundle.getKeys().each {key ->
        sb.append(sep);
        sb.append(key.replace('.', '_'));
        sb.append(': "');
        sb.append(bundle.getString(key).replace('"', '&quot;'));
        sb.append('"\n');
        sep = ',';
    }
    sb.append('};\n</script>\n')
    render(text: sb.toString());
}

}

Upvotes: 1

Related Questions