Last updated by 5 years ago

Page: Dynamic Locale change, Version:0

I've been working on a plugin for Grails to allow dynamic switching of locales, management of keys and values, etc.

In the interim, I am publishing this quick and dirty solution (meaning, it's not optimal, but it'll work for now until I finish the rest of the code)

I need to play more with Filters I was having a lot of problems with the Filters, but for now, I have a few beforeInterceptor lines you add to each Controller. In your link tags you add simple params with the locale, and finally the class that does all the work.

import org.g2.LocaleChangeFromURI

//add to the top of each Controller you want to change locales on the fly def beforeInterceptor = [action:this.&localeChange]

def localeChange = { LocaleChangeFromURI.localeChange(params, request, response) }

//if you have a requirement that the locale be passed on every link, then you can add the following to your g:link tags

Create a package structure under src/groovy called org.g2 (or whatever) and put this class there. You're now set.

package org.g2;

import as RCU;

/** * Adds the ability to change the locale from the request parameters * It does need to be called from the top of your Controllers */ class LocaleChangeFromURI { def static localeChange = {params, request, response -> def attrs = params?.locale if (attrs) { def sp = attrs.split("_") def language def country def variant

sp.eachWithIndex {ita, idx -> switch (idx) { case 0: language = ita break; case 1: country = ita break; case 2: variant = ita break; } }

def locale

if (language) { locale = new Locale(language, country ?: "", variant ?: "") } else { locale = RCU.getLocale(request) }

RCU.getLocaleResolver(request).setLocale(request, response, locale) } } }

To test against Grails, simply go to any of your scaffold pages and put ?locale=zh_CN or whatever your locale is.

You may be yelling at your monitor… this doesn't work! Actually, it does and quite well… to test put the following snippet at the top of the page you're looking at <g:message code="default.doesnt.match.message"/>

The display should match that from properties files.

Remember the key must have a definition in the properties files OR when doing default scaffolding generated titles and titleKeys are made e.g. _(title="Id" titleKey="")_. The i18n plugin addresses this issue to some degree. In short, if you put the key into your properties files and give it a value, then that value will be used instead of the default provided by the scaffolding.

Back to work on the plugin.