Grails: Simple locale/language selector

How you can change locales in Grails is described in the Reference Documentation. Normally you want to do this in form of a language selector. Here’s an example taglib how you can do that:

import org.springframework.web.servlet.support.RequestContextUtils;
import groovy.xml.MarkupBuilder;

class LocaleTagLib {
	static namespace = 'locale'
	
	List<Locale> locales = [Locale.GERMAN, Locale.ENGLISH]

	/**
	 * Renders a locale selector. 
	 * Adds the class <code>active</code> to the list-element of the current language. 	
	 */
	def selector = {
		Locale requestLocale = RequestContextUtils.getLocale(request)
		
		MarkupBuilder mb = new MarkupBuilder(out)
		mb.ul('id': 'locale-selector') {
			locales.each { Locale locale ->
				li(requestLocale.language == locale.language ? ['class': 'active'] : [:]) {
					mb.yield(
						link( controller: controllerName, action: actionName, params: params + [lang: locale.language], 
							 { locale.getDisplayLanguage(locale) } ).toString(),
						false 
						)
				}
			}
		}
	}
}

What you probably have to change is the collection of locales. You don’t have to provide messages for the locales, the getDisplayLanguage()-method of Locale provides the translation.

Usage:

<locale:selector />

.

Advertisements
Posted in Grails. Tags: , . 3 Comments »