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.  

5 Comments

RSS feed for comments on this post.

  1. Thanks you for a nice solution.

    Pozdrawiam, Szymon

    Comment by Szymon Polom — July 25, 2010 #

  2. […] Grails url mapping localization Теги: grails, localization […]

    Pingback by Grails: dynamic locale change < Stanfy Блог — November 19, 2010 #

  3. Unfortunately this code doesn’t work in Grails 1.3.7:
    out << link(attrs, body)

    But you can fix it, just change some parts.

    1) import this:
    import org.codehaus.groovy.grails.plugins.web.taglib.*
    class BaseTagLib {...

    and applicationTagLib.link.call(attrs, body) instead of out << link(attrs, body)

    Comment by Vladimir — June 25, 2011 #

  4. Oh, sorry, I forgot one peace of code.

    You have to add
    def applicationTagLib = grailsApplication.mainContext.getBean('org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib')

    before
    applicationTagLib.link.call(attrs, body)

    Comment by Vladimir — June 25, 2011 #

  5. Thank you very much for this article. it saved me lots of time.

    Comment by Logo Design — July 13, 2011 #

Sorry, the comment form is closed at this time.

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