Grails - getting a message value from controller

22,028

Solution 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())
  ...
}

Solution 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)
Share:
22,028
armandino
Author by

armandino

I maintain a couple of open source projects: Instancio: a library with a JUnit 5 extension for automating data setup in unit tests. TxtStyle: a command line tool for colorizing output of text console programs using regular expressions. I'm always open to new project opportunities: https://www.linkedin.com/in/armandino https://www.thinkthru.ca

Updated on July 09, 2022

Comments

  • armandino
    armandino almost 2 years

    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?