GRAILS specific LOCALE Handling – Change Language and return to the same page

14 / Sep / 2010 by Salil 0 comments

It’s common requirement when we work on some portal – we need to provide support for various languages.
messages.properties/ResourceBundle is out of the scope of this post. Here I am just mentioning –

how to switch to a different language taking an advantage of GRAILS

On your view (gsp) page add following –

<%
String targetUri = (request.forwardURI - request.contextPath);
%>
 English
 French
 Spanish
.....
.....

I just wanted to give you a rough idea. But you can create a custom tag for this – depending upon your requirement.

Now the trick here is to send parameter with name “lang”. And GRAILS automatically recognizes it and set locale itself.
Following is the code at server side (controller/action).

//import org.springframework.context.i18n.LocaleContextHolder
//import org.springframework.web.servlet.support.RequestContextUtils as RCU;

class LangController {
def lang = {
       String targetUri = params.targetUri ? params.targetUri : "/"
       // String language = params.lang ? params.lang : 'en'
       // LocaleContextHolder.setLocale(new Locale(language))
       // RCU.getLocaleResolver(request).setLocale(request, response, new Locale(language))
       redirect(uri: targetUri)
}
}

If you notice above, I have commented out few lines (with the help of grails internal implementation, we need to do nothing explicitly to switch to a different language).

So in SINGLE LINE:

Base URL: http://example.com/cont/act/id  
Locale specific URL: http://example.com/cont/act/id?lang=fr 

Hope it helps!
Salil Kalia

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *