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!!!
![]() | Published on August 7th, 2008 | | Posted by Roman Mackovcak |
August 8th, 2008 at 9:39
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
August 8th, 2008 at 11:18
Ooops! You are right. Corrected.
December 11th, 2008 at 4:34
[…] 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 […]
January 6th, 2009 at 20:32
[…] – 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 & […]
May 27th, 2010 at 18:53
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.
August 7th, 2010 at 8:41
import org.codehaus.groovy.grails.commons.ApplicationHolder