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 »

3 Responses to “Grails: Simple locale/language selector”

  1. Sherif Says:

    Very nice tag lib , but how to use it for Arabic language ?

    • Martin Hofmann Says:

      There is no constant for arabic. But you can create the locale:

      List locales = [new Locale(“ar”), Locale.ENGLISH]

  2. stokito Says:

    Here is plugin for this http://grails.org/plugin/lang-selector
    I never used it but think it would be good to mention it in your article


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: