thomers
thomers

Reputation: 2693

Retrieve active locale in Grails application

I know I can use the "lang" parameter to automatically change the current locale as described in the docs, but how do I track those changes, for example to update the language stored in the current user domain object?

request.locale does not work, since it does not reflect the changes done via "?lang=xx"

Upvotes: 19

Views: 13019

Answers (4)

Topera
Topera

Reputation: 12389

You can also use the LocaleContextHolder which doesn't need a request as a parameter

import org.springframework.context.i18n.LocaleContextHolder;

LocaleContextHolder.getLocale();

Upvotes: 13

Joshua Moore
Joshua Moore

Reputation: 24776

Within your controller you can obtain the locale using the RequestContextUtils.

import org.springframework.web.servlet.support.RequestContextUtils as RCU

Then to resolve the locale for the request:

RCU.getLocale(request)

Upvotes: 36

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93333

If you display properties of RequestContextUtils.getLocale(request) , you will find the following :

ISO3Country= 
ISO3Language=ara 
displayCountry= 
class=class java.util.Locale 
default=fr_FR 
language=ar 
variant= 
ISOLanguages=[Ljava.lang.String;@4269f8e3 
availableLocales=[Ljava.util.Locale;@3b532125 
displayName=arabe 
ISOCountries=[Ljava.lang.String;@4ea52290 
displayVariant= 
displayLanguage=arabe 
country=

Upvotes: 0

Lauri Piispanen
Lauri Piispanen

Reputation: 2097

Grails uses Spring internally. You can get the current locale from Spring's RequestContextUtils: http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/servlet/support/RequestContextUtils.html#getLocale(javax.servlet.http.HttpServletRequest)

import org.springframework.web.servlet.support.RequestContextUtils

def locale = RequestContextUtils.getLocale(request)

Check <g:message> tag source for more info:

http://grails.org/doc/latest/ref/Tags/message.html

Upvotes: 13

Related Questions