Search code examples
grailswebinternationalizationrequestlocale

Grails - Change locale behavior to use dash instead of underscore


I'm writing a Grails application that get's it's locale from a 3rd party like so:

my.app.com?lang=en-US since Grails uses en_US it throws the exception Error intercepting locale change: Locale part "en-US" contains invalid characters

How can I intercept the request prior to PageFragmentCachingFilter, in order to fix the locale code?

Is there a better approach?


Solution

  • One way to override the default behavior is to register a CustomLocaleChangeInterceptor as a bean in resources.groovy as

    beans = {
        localeChangeInterceptor(your.package.CustomLocaleChangeInterceptor) {
            paramName = "lang"
        }
    }
    

    GIST
    The idea is to override the default localeChangeInterceptor which is the default interceptor in i18n grails plugin in order to take care of the hyphenated locale string in the request url parameter. Main logic to look at in the custom locale interceptor is:

    try {
            // choose first if multiple specified
            if (localeParam.getClass().isArray()) {
                localeParam = ((Object[])localeParam)[0]
            }
    
            //If locale hyphenated, then change to underscore
            if(localeParam.toString()?.contains('-')){
                localeParam = StringUtils.replace(localeParam.toString(), "-", "_")
            }
    
            def localeResolver = RequestContextUtils.getLocaleResolver(request)
            def localeEditor = new LocaleEditor()
            localeEditor.setAsText localeParam.toString()
            localeResolver?.setLocale request, response, (Locale)localeEditor.value
            return true
        }
        catch (Exception e) {
            return true
        }