【问题标题】:Grails: Reading the Resource BundleGrails:读取资源包
【发布时间】:2012-02-22 18:14:49
【问题描述】:

我尝试从资源包中获取消息/翻译列表,但失败(引发异常)。该应用程序正在 IDEA 的 Tomcat 上运行:

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

这里有什么问题。 i18n/dictionary 在类路径上。可能是 'i18n/dictionary' 是错误的。

我能够获取消息源,但我无法从此 (SPRING) 对象获取密钥:

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

【问题讨论】:

    标签: spring grails resourcebundle


    【解决方案1】:

    资源路径不完整。如果你需要前端的翻译表,也许下面的控制器会很有用:

    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());
    }
    

    }

    【讨论】:

    • 不要自己构建JSON,使用JsonBuilder
    猜你喜欢
    • 2016-03-05
    • 1970-01-01
    • 2012-04-11
    • 2012-10-03
    • 2014-03-17
    • 1970-01-01
    • 1970-01-01
    • 2012-11-19
    • 1970-01-01
    相关资源
    最近更新 更多