Grails - getting a message value from controller

北慕城南 提交于 2019-11-27 00:28:39

问题


How can I get a value from message properties outside of GSPs? For instance, the equivalent of

<g:message code="some.message"/>

but in a controller?


回答1:


Inside a controller or a taglib, you can use the following :

g.message(code: 'some.message')

However, inside domain classes or services, you need to inject messageSource and call getMessage() method from Sping class AbstractMessageSource. This snippet shows you how to do that:

import org.springframework.context.i18n.LocaleContextHolder as LCH
...
class MyServiceOrMyDomain {
  def messageSource 
  ...
  messageSource.getMessage(code, msgArgs, defaultMsg, LCH.getLocale())
  ...
}



回答2:


You can also import the validation tag lib and use it grab the message source.

import org.codehaus.groovy.grails.plugins.web.taglib.ValidationTagLib
def g = new ValidationTagLib()
g.message(error: error)


来源:https://stackoverflow.com/questions/2814771/grails-getting-a-message-value-from-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!