31

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?

armandino
  • 17,625
  • 17
  • 69
  • 81

2 Answers2

49

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())
  ...
}
fabien7474
  • 16,300
  • 22
  • 96
  • 124
  • 1
    Just in order to help someone who might have the same problem as I did - myArgs has to be an array of Objects, for example: messageSource.getMessage("some.code", ["arg1"] as Object[], "default", LCH.getLocale()) – MBozic Oct 10 '12 at 17:58
  • 2
    I'm using grails 2.1. It looks like you cannot use the g namespace in controllers. Using message(code: "") does the job. Maybe you only need the g namespace for taglibs now. http://grails.org/doc/2.1.0/guide/single.html#i18n – Thomas Buckley Jan 22 '13 at 14:04
  • 1
    I was getting: `java.lang.NullPointerException: Cannot invoke method getMessage() on null object` in a Grails 2.5.6 domain class with the domain version mentioned. Instantiating the member variable messageSource helped me out: `def messageSource = grails.util.Holders.applicationContext.getBean("messageSource")` – philburns Jun 02 '22 at 13:35
13

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)
Blacktiger
  • 1,275
  • 1
  • 9
  • 19
  • 1
    But does it compute the locale of the current request? – fabien7474 May 12 '10 at 15:17
  • 1
    `g.message` seems to be a better way than `messageSource` because require less code, you don't have to handle exceptions and you already know [how to use it](http://grails.org/doc/latest/ref/Tags/message.html). – César Sep 24 '13 at 17:39