【问题标题】:Setting message i18n dynamically in Grails在 Grails 中动态设置消息 i18n
【发布时间】:2013-10-17 15:35:44
【问题描述】:

我正在尝试向 Grails 中的 i18n messageSource 添加一些附加值。

默认的 message.properties 工作正常,但我需要从远程资源加载一些附加值(我知道这不好,但你知道,管理...)。

我正在尝试通过 Boostrap.groovy 加载这些变量 示例:

def messageSource = new StaticMessageSource()
messageSource.addMessage("key1", new Locale("en"), "English Value")
messageSource.addMessage("key2", new Locale("de"), "Other Language Value")

当我尝试通过

在任何 GSP 中访问它们时
<g:message code="key1" /> 

只返回键,就好像在 StaticMessageSource 中根本没有设置值一样。显然我对文档不太满意。

Grails 网站上没有任何内容,SpringFramework 上几乎没有。 将不胜感激任何建议。

还有什么方法可以将一组消息添加到 messageSource Session 中!?

【问题讨论】:

    标签: spring grails grails-2.0


    【解决方案1】:

    messageSource bean 在 Grails 中声明为 PluginAwareResourceBundleMessageSource 类。当我需要更多功能时,我会创建一个 grails plugin 并配置上下文以加载我的类而不是 Grails 类。

    类似:

    src/groovy/MyMessageSource.groovy

    class MyMessageSource extends PluginAwareResourceBundleMessageSource {
      String getMessage(String key, Object[] args, Locale locale) {
        String message
        //handle your custom keys
        if(key.contains('myCoolMessagePrefix') {
        } else {
          //or delegate to the default of Grails
          message = super.getMessage(key, args, locale)
        }
    
        return message
      }
    }
    

    插件描述符 -> MyMessagesGrailsPlugin.groovy

    def doWithSpring = { 
      //here we change the bean definition to use the customized messagesource
      def beanconf = springConfig.getBeanConfig('messageSource')
      def beandef = beanconf ? beanconf.beanDefinition : springConfig.getBeanDefinition('messageSource')
    
      if (beandef) {
        beandef.beanClassName = MyMessageSource.class.name
      }
    }
    

    【讨论】:

      【解决方案2】:

      我通过以下方式解决了类似的问题:

      1. 在 grailsApplication.config 中设置自定义消息代码(您可以 只要你能从你的 自定义消息源)
      2. 扩展 PluginAwareResourceBundleMessageSource
      3. 覆盖resolveCode 和resolveCodeWithArguments,检查您的 自定义来源
      4. 使用“应用程序”引用(它在基类中)来获取 配置
      5. 在resources.groovy中重新定义消息源:

      messageSource(MyMessageSource) { bean -> bean.autowire = "byName" //-这很重要 basenames = "WEB-INF/grails-app/i18n/messages" }

      【讨论】:

      • 仅更改 bean 定义而不是声明 messageSource 将为您提供让 Grails i18n 插件配置 bean 的选项。如果你看一下 I18nGrailsPlugin,它不仅仅是基本名称。
      • 帮助很大。谢谢!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-10
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      相关资源
      最近更新 更多