Grails Goodness: Change Locale With Request Parameter
Grails has internationalisation (i18n) support built-in. It is very easy to add messages for different locales that can be displayed to the user. The messages are stored in properties files in the directory grails-app/i18n
. Grails checks the request Accept-Language header to set the default locale for the application. If we want to force a specific locale, for example for testing new messages we added to the i18n property files, we can specify the request parameter lang. We specify a locale value and the application runs with that value for new requests.
The following screenshot shows a scaffold controller for a Book
domain class with a default locale en:
To see a dutch version we invoke the controller with the lang request parameter: http://localhost:8080/book/create?lang=nl
:
We can change the name of the request parameter by redefining the Spring bean localeChangeInterceptor
in for example grails-app/conf/spring/resources.groovy
:
import org.grails.web.i18n.ParamsAwareLocaleChangeInterceptor
beans = {
localeChangeInterceptor(ParamsAwareLocaleChangeInterceptor) {
paramName = "locale"
}
}
Written with Grails 3.0.10