MultiLingual电子邮件模板与grails

时间:2013-09-06 05:52:54

标签: grails grails-2.0 grails-plugin

我正在尝试从grails发送电子邮件,邮件模板应该是多语言的。

我发现我们可以将GSP渲染为字符串,甚至可以在Grails邮件插件中渲染GSP。

现在我在GSP中阅读来自messages.properties的静态消息,假设我会为每种语言定义,而我的电子邮件会多语言。

现在这是我面临的问题

在模板中,语言始终设置为en_US。我使用以下API来获取模板的字符串。我没有直接使用邮件插件,因为我需要将发送消息作为字符串存储到数据库中

    def contents = groovyPageRenderer.render(template:"/layouts/emailparse", model:[mailObj: mailObj])

我还在论坛上的其他帖子上阅读了有关使用lang参数设置语言的信息,但语言仍设置为en_US。

上述方法是否会调用支持指定语言? 有没有选择使用力度模板来做这种多语种邮件?

2 个答案:

答案 0 :(得分:1)

如果您是从请求处理线程(例如来自控制器操作)发送邮件,那么它应该自动从请求中选择正确的区域设置。如果您从后台线程发送,那么它将不知道要使用的语言环境,因为没有“当前请求”上下文。

如果您有其他方法可以使用正确的语言(例如,如果您将每个用户的首选语言存储在数据库中),那么您可以重置LocaleContextHolder

def savedContext = LocaleContextHolder.getLocaleContext()
LocaleContextHolder.setLocale(correctLocaleForThisUser)
try {
  def contents = groovyPageRenderer.render(template:"/layouts/emailparse", model:[mailObj: mailObj])
  // etc. etc.
} finally {
  LocaleContextHolder.setLocaleContext(savedContext)
}

确切地说,correctLocaleForThisUser的确定方式取决于您的申请。您可以将每个用户的首选语言存储为数据库中User域对象的属性,或者如果您使用控制器操作中的executor plugin's runAsync之类的内容,那么您可以保存请求区域设置有权访问它,然后在异步任务中重复使用它:

// SomeController.groovy
def sendEmail() {
  // get locale from the thread-local request and save it in a local variable
  // that the runAsync closure can see
  Locale localeFromRequest = LocaleContextHolder.getLocale()
  runAsync {
    def savedContext = LocaleContextHolder.getLocaleContext()
    // inject the locale extracted from the request
    LocaleContextHolder.setLocale(localeFromRequest)
    try {
      def contents = groovyPageRenderer.render(template:"/layouts/emailparse", model:[mailObj: mailObj])
      // etc. etc.
    } finally {
      LocaleContextHolder.setLocaleContext(savedContext)
    }        
  }
}

答案 1 :(得分:0)

您是否可以通过创建包含具有正确翻译的列表的模型来解决此问题?

例如:

def messages = [:]
messages['hello.world'] = messageSource.getMessage(
        "hello.world",
        null,
        new Locale("nb")
)
def template = groovyPageRenderer.render(
        template: '/mail/email',
        model:[messages:messages]
)

然后在视图中你写道:

<html>
    <head>
       <title>${messages['hello.world']}</title>
    </head>
    <body>
    </body>
</html>
相关问题