Grails: How to access i18n from controller or service?

I know there is an answer, but here's my take at it. I have made a service (inspired by others)

import org.springframework.web.servlet.i18n.SessionLocaleResolver
import org.springframework.context.MessageSource

class I18nService {

    boolean transactional = false

    SessionLocaleResolver localeResolver
    MessageSource messageSource

    /**
     *
     * @param msgKey
     * @param defaultMessage default message to use if none is defined in the message source
     * @param objs objects for use in the message
     * @return
     */
    def msg(String msgKey, String defaultMessage = null, List objs = null) {

        def msg = messageSource.getMessage(msgKey,objs?.toArray(),defaultMessage,localeResolver.defaultLocale)

        if (msg == null || msg == defaultMessage) {
            log.warn("No i18n messages specified for msgKey: ${msgKey}")
            msg = defaultMessage
        }

        return msg
    }

    /**
     * Method to look like g.message
     * @param args
     * @return
     */
    def message(Map args) {
        return msg(args.code, args.default, args.attrs)
    }
}

Now, in a service just inject i18nService and you're good to go! This also makes unit testing of other service a breeze as you can mock the i18nService

As a bonus, the service will attempt to find the current locale for the current webrequest, taken that the service runs in a webrequest context.


If you are using grails 1.3.7, you need to declare message source as :

def messageSource

This way it will be injected into your controller. I think in 2.0 you can do it the way you posted, but it even so, I think it is worth a try to declare it as stated above.


In Grails 2.2.3 it should work:

import org.springframework.context.MessageSource
...
def MessageSource messageSource
...
String subject = messageSource.getMessage("somemessagekey", [name], null)
...

Reference link and more possibilities here: http://static.springsource.org/spring/docs/2.0.8/api/org/springframework/context/MessageSource.html

Tags:

Grails