Grails url mapping localization

This is simple "hack" that allows you to internationalize your url in your Grails (1.2.x) application. Lets say that we have application that is provided in two languages: Polish and English. Create ours controller:

  1.  
  2. FooController {
  3. def bar {
  4. }
  5. }
  6.  

In ours locale files (message_pl.properties and message_en.properties) add "locale" param (because grails bug) with code specified for this file (pl, en).

Next step is to create new taglib that will generate internationalized link:

  1.  
  2. class BaseTagLib {
  3. def localizedLink = { attrs, body ->
  4. attrs.mapping = message(code:'locale') + StringUtils.toUpperCaseFristLetter(attrs.mapping)
  5. out << link(attrs, body)
  6. }
  7. }
  8.  

This Taglib doing nothing than add prefix for name of the route. It use util method StringUtils.toUpperCaseFristLetter, that capitalize first letter of provided string:

  1.  
  2. class StringUtils {
  3. static def toUpperCaseFristLetter(String text){
  4. text[0].toUpperCase() + text[1..-1]
  5. }
  6. }
  7.  

Now we can provide url mappings as:

  1.  
  2. class UrlMappings {
  3. static mappings = {
  4. name enGoToFooBar:'/go/to/foo/Bar' {
  5. controller = 'foo'
  6. action = 'bar'
  7. }
  8.  
  9. name plGoToFooBar:'/idz/do/foo/Bar' {
  10. controller = 'foo'
  11. action = 'bar'
  12. }
  13. }
  14. }
  15.  

In ours gsp files we can use it like:

  1.  
  2. <g:localizedLink mapping="goToFooBar"><g:message code="text.goToFooBar" /></g:localizedLink>
  3.  

Powered by WordPress with GimpStyle Theme design by Horacio Bella.
Entries and comments feeds. Valid XHTML and CSS.