I am back with a new blog post titled “Locale and Message Bundle in Grails”. In grails we define all the string content/description in message.properties file. In order to fetch the message in gsp page we can use the following code:-

<g:set var="eName" value="${g.message(code: 'employee.name', args: ['Vivek'])} " />;

and if we have a message defined as :-

employee.name = Employee name {0}

then the content of eName will be “Employee name Vivek”.

We can also use the g tag like this:-

<g:message code="my.message.code" />;

If you want to use message.properties in Service/Controller then you need to inject the bean like this:-

private MessageSource messageSource;

and then use the following code:

messageSource.getMessage('employee.name', null, LocaleContextHolder.locale)

The second argument is passed as null if there are no parameters defined in message. If we want to pass argument we can do it in the following way:-

Object[] parameters = ["Vivek"]
messageSource.getMessage('employee.name', parameters, LocaleContextHolder.locale)

As per the Grails documentation: LocaleContextHolder.locale returns the Locale associated with the current thread.

First of all lets define Locale. A locale is a set of parameters that defines the user’s language, country and any local preferences.

By default the user locale is detected from the incoming Accept-Language header. However, we can use the parameter named “lang” in grails to switch the user locale like:-

/order/list?lang=de

We can also set the default locale in grails by using the following code in resources.groovy file:-

beans = {
   localeResolver(org.springframework.web.servlet.i18n.SessionLocaleResolver) {
      defaultLocale = new Locale("de","DE")
      java.util.Locale.setDefault(defaultLocale)
   }
}

That was all!
Thanks 🙂