Grails: internationalization in the service

Today I spent some time by creation of localized messages in a service. Here is a small tutorial.

1. Create your service

grails create-service Local

2. Add a messageSource variable to your new service

class LocalService {
  def messageSource
}

3. Use it in a service method

// Initialize parameters
Object[] testArgs = {}
def msg = messageSource.resolveCode("message.code.to.translate", new java.util.Locale("EN")).format(testArgs)

4. Finally edit the grails-app/i18n/messages.properties

message.code.to.translate=It works!!!

6 Responses to “Grails: internationalization in the service”

  1. Lee Butts Says:

    Hi Roman,

    is it necessary to add the code to resources.groovy? Shouldn’t the messageSource automatically be injected into the service by name?

    cheers

    Lee

  2. Roman Mackovcak Says:

    Ooops! You are right. Corrected.

  3. Recent Links Tagged With "localservice" - JabberTags Says:

    […] public links >> localservice Grails internationalization in the service Saved by torkar on Wed 19-11-2008 What is Wmiprvse.exe? Saved by avc76 on Tue 04-11-2008 […]

  4. Websites tagged "grails" on Postsaver Says:

    […] – Links to help you answer why choose Grails as your web framework? saved by boulder22008-12-25 – Grails internationalization in the service saved by aaronholz2008-12-22 – My OSCON Aftermath saved by joaom2008-12-20 – Beginnin Groovy & […]

  5. Philip Says:

    Personally I would rather get the application taglib from the app context and use it like in the rest of the application.
    Like having this on a tools-class

    def getApplicationTagLib(){
    def ctx = ApplicationHolder.getApplication().getMainContext()
    return ctx.getBean(‘org.codehaus.groovy.grails.plugins.web.taglib.ApplicationTagLib’)
    }

    And then you can do in your service method

    def g = xyzTools.getApplicationTagLib()
    def msg = g.message(code:’message.code.to.translate’)

    That way you wouldn’t have to worry about passing the locale etc.

  6. Werner Says:

    import org.codehaus.groovy.grails.commons.ApplicationHolder