SlideShare a Scribd company logo
1 of 26
Download to read offline
Grails - Internationalization
Nakul Ashish Pant
Agenda
Introduction
Why Internationalization
Localizing Messages
Using Parameterized Messages
messageSource / g.message
Summary
Introduction
Web applications are really easy to distribute.Web Applications need to adapt
and behave differently under different situations
For a request from Spain the application might want to display messages in
spanish and in english when request is made from New York
The adaptations made by the application may involve more complexity than
simply displaying different versions of text. An application may need to impose
different business rules based on the origin of a particular request.
Let’s see what Grails has in
its arsenal for this problem?
Localizing Messages
One way of providing this capability is to have a separate version of the
application for each language you want to target. That approach has lots of
problems.
Maintaining all those different versions and trying to keep them all in sync
would be an awful lot of work. A much better idea is to have a single version of
the application that is flexible enough to display messages in various
languages using localized messages.
Localizing messages Continued ..
To support localized messages in your Grails application, you should be defining all
user messages in a properties file.
User messages should not be hard-coded in GSP pages, GSP templates, or
anywhere else.
Having messages in a properties file allows you to maintain all of them all in a single
place.
It also lets you take advantage of the localization capabilities provided by Grails.
I18n directory structure
I18n Directory Structure Continued ..
When a Grails app is created, the project includes a number of localized property
files in the grails-app/i18n/ directory
The messages.properties file in the grails-app/i18n/ directory contains default
validation messages in English. These messages are used when validation fails in a
domain class or command object.
In addition to the default messages.properties file, this directory has several other
properties files that contain the same messages in other languages. For example,
“es” is the language code for Spanish, so messages_es.properties contains
validation messages in Spanish.
I18n Directory Structure Continued ..
Example of a properties file - application.properties
app.grails.version=2.4.4
app.name=smartly
app.servlet.version=3.0
app.version=0.1
Property files are plain text files, which contain name-value pairs.
Retrieving Messages
// GroovyMessages.groovy
def messages = ResourceBundle.getBundle('messages')
def appName = messages.getString('app.name')
println "application name is ${appName}"
Retrieving Messages - message Tag
<body>
...
<g:message code="app.smartly.welcome"/>
... </body>
The code attribute tells the message tag which property value should be retrieved.
By default, Grails will decide which version of the property file to use based on the
locale of the current web request.
A simple way to test your Grails application’s localization is to include a request
parameter named lang and assign it a valid language code, such as “es” for
Spanish
Using URLMapping
A URL Mapping for Localization
class UrlMappings {
static mappings = {
"/store/$lang"(controller:'store')
// ...
}
}
This mapping will map all requests to a URL such as http://localhost:
8080/smartly/en/ or http://localhost:8080/smartly/es/, where “en” and “es” could be
any valid language code.
Demo
g:message
Using Parameterized Messages
Often a user message may consist of more than simple static text.
The message may need to include some data that is not known until runtime.
Defining a Parameterized Message
# messages.properties
gtunes.purchased.songs=You have purchased ({0}) songs.
Continued
java.text.MessageFormat class uses a zero-based index
{0} in the message is a placeholder for the value of the first parameter.
If the message had multiple parameters, they would be represented in the
value of the message with placeholders like {0}, {1}, {2}, and so on.
The message tag supports an optional parameter named args, and if that
parameter is assigned a value, its value will be treated as a list of
parameters that need to be applied to the message.
Continued
gtunes.purchased.songs=You have purchased [{0}] songs
<div>
<g:message code="gtunes.purchased.songs" args="[97]"/>
</div>
Demo
parameterized messages!
Using messageSource
Grails provides a bean named messageSource that can be injected into any
Grails artefact, including controllers, taglibs, other beans, and so on.
The messageSource bean is an instance of the org.springframework.context.
MessageSource interface
This interface defines three overloaded versions of the getMessage method for
retrieving messages from the source.
Using messageSource Continued ..
String getMessage(String code, Object[] args, Locale locale)
String getMessage(String code, Object[] args, String defaultMessage, Locale locale)
String getMessage(MessageSourceResolvable resolvable, Locale locale)
Since the messageSource bean participates in Grails’s dependency autowiring
process, all you need to do to get a reference to the bean is declare a property named
messageSource in your Grails artefact.
Using messageSource Continued ..
package com.gtunes
class StoreService {
def messageSource
def someServiceMethod() {
def msg = messageSource.getMessage('gtunes.my.music', null, null)
// ...
}
...
}
Note that the second and third arguments are null. The second argument is an Object
[], which would be used to pass parameters to a parameterized message. The third
argument is a java.util.Locale, which may be specified to retrieve a message for any
Locale other than the default Locale for this request.
Using messageSource Continued ..
Example -
class StoreService {
def messageSource
def someServiceMethod() {
def msg = messageSource.getMessage('gtunes.my.music',null,Locale.ITALIAN)
// …
}
...
}
Using g.message
From within a Controller or TagLib artefact, a simpler way to retrieve messages
is to invoke the
message GSP tag as a method on the special g namespace variable available
in those artefacts
def index() {
def msg = g.message(code:'gtunes.my.music')
} //All tag libraries are accessible using the very same technique.
Demo
messageSource/g.message
Summary
Retrieving messages from a property file is a snap in a Grails application. The
message tag is very easy to access and use from GSP pages and GSP
templates. The messageSource bean is easily accessible from wherever the
application may need it. All of these enhancements are built on top of proven
and well-understood Java-platform tools, including java.text. MessageFormat
and org.springframework.context.MessageSource.
Questions ?
Thank You !

More Related Content

Similar to Grails Internationalization

WordPress Theme Workshop: Internationalization
WordPress Theme Workshop: InternationalizationWordPress Theme Workshop: Internationalization
WordPress Theme Workshop: InternationalizationDavid Bisset
 
BarCamp KL H20 Open Social Hackathon
BarCamp KL H20 Open Social HackathonBarCamp KL H20 Open Social Hackathon
BarCamp KL H20 Open Social Hackathonmarvin337
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core ModuleKatie Gulley
 
Android application structure
Android application structureAndroid application structure
Android application structureAlexey Ustenko
 
Localization and Shared Preferences in android
Localization and Shared Preferences in androidLocalization and Shared Preferences in android
Localization and Shared Preferences in androidAly Arman
 
AndroidLab_IT.pptx
AndroidLab_IT.pptxAndroidLab_IT.pptx
AndroidLab_IT.pptxAhmedKedir9
 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lineslokeshG38
 
JSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupJSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupManjuKumara GH
 
3.1 file input and output
3.1   file input and output3.1   file input and output
3.1 file input and outputallenbailey
 
ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsSaurabh Narula
 
Service Layer in PHP | StudySection
Service Layer in PHP | StudySectionService Layer in PHP | StudySection
Service Layer in PHP | StudySectionStudy Section
 
03 android application structure
03 android application structure03 android application structure
03 android application structureSokngim Sa
 
Golang proto buff_ixxo
Golang proto buff_ixxoGolang proto buff_ixxo
Golang proto buff_ixxowww.ixxo.io
 
Drupal 8 customized checkout system
Drupal 8 customized checkout systemDrupal 8 customized checkout system
Drupal 8 customized checkout systemAhmad Hassan
 
Net framework key components - By Senthil Chinnakonda
Net framework key components - By Senthil ChinnakondaNet framework key components - By Senthil Chinnakonda
Net framework key components - By Senthil Chinnakondatalenttransform
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdfSudhanshiBakre1
 

Similar to Grails Internationalization (20)

WordPress Theme Workshop: Internationalization
WordPress Theme Workshop: InternationalizationWordPress Theme Workshop: Internationalization
WordPress Theme Workshop: Internationalization
 
BarCamp KL H20 Open Social Hackathon
BarCamp KL H20 Open Social HackathonBarCamp KL H20 Open Social Hackathon
BarCamp KL H20 Open Social Hackathon
 
Questions On The Code And Core Module
Questions On The Code And Core ModuleQuestions On The Code And Core Module
Questions On The Code And Core Module
 
S/MIME
S/MIMES/MIME
S/MIME
 
Android application structure
Android application structureAndroid application structure
Android application structure
 
Adobe Flex4
Adobe Flex4 Adobe Flex4
Adobe Flex4
 
Localization and Shared Preferences in android
Localization and Shared Preferences in androidLocalization and Shared Preferences in android
Localization and Shared Preferences in android
 
AndroidLab_IT.pptx
AndroidLab_IT.pptxAndroidLab_IT.pptx
AndroidLab_IT.pptx
 
Android coding guide lines
Android coding guide linesAndroid coding guide lines
Android coding guide lines
 
concept of oops
concept of oopsconcept of oops
concept of oops
 
JSON Logger Baltimore Meetup
JSON Logger Baltimore MeetupJSON Logger Baltimore Meetup
JSON Logger Baltimore Meetup
 
3.1 file input and output
3.1   file input and output3.1   file input and output
3.1 file input and output
 
ActionScript 3.0 Fundamentals
ActionScript 3.0 FundamentalsActionScript 3.0 Fundamentals
ActionScript 3.0 Fundamentals
 
Service Layer in PHP | StudySection
Service Layer in PHP | StudySectionService Layer in PHP | StudySection
Service Layer in PHP | StudySection
 
03 android application structure
03 android application structure03 android application structure
03 android application structure
 
The smartpath information systems c plus plus
The smartpath information systems  c plus plusThe smartpath information systems  c plus plus
The smartpath information systems c plus plus
 
Golang proto buff_ixxo
Golang proto buff_ixxoGolang proto buff_ixxo
Golang proto buff_ixxo
 
Drupal 8 customized checkout system
Drupal 8 customized checkout systemDrupal 8 customized checkout system
Drupal 8 customized checkout system
 
Net framework key components - By Senthil Chinnakonda
Net framework key components - By Senthil ChinnakondaNet framework key components - By Senthil Chinnakonda
Net framework key components - By Senthil Chinnakonda
 
Global objects in Node.pdf
Global objects in Node.pdfGlobal objects in Node.pdf
Global objects in Node.pdf
 

Recently uploaded

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....ShaimaaMohamedGalal
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 

Recently uploaded (20)

DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Clustering techniques data mining book ....
Clustering techniques data mining book ....Clustering techniques data mining book ....
Clustering techniques data mining book ....
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 

Grails Internationalization

  • 2. Agenda Introduction Why Internationalization Localizing Messages Using Parameterized Messages messageSource / g.message Summary
  • 3. Introduction Web applications are really easy to distribute.Web Applications need to adapt and behave differently under different situations For a request from Spain the application might want to display messages in spanish and in english when request is made from New York The adaptations made by the application may involve more complexity than simply displaying different versions of text. An application may need to impose different business rules based on the origin of a particular request.
  • 4. Let’s see what Grails has in its arsenal for this problem?
  • 5. Localizing Messages One way of providing this capability is to have a separate version of the application for each language you want to target. That approach has lots of problems. Maintaining all those different versions and trying to keep them all in sync would be an awful lot of work. A much better idea is to have a single version of the application that is flexible enough to display messages in various languages using localized messages.
  • 6. Localizing messages Continued .. To support localized messages in your Grails application, you should be defining all user messages in a properties file. User messages should not be hard-coded in GSP pages, GSP templates, or anywhere else. Having messages in a properties file allows you to maintain all of them all in a single place. It also lets you take advantage of the localization capabilities provided by Grails.
  • 8. I18n Directory Structure Continued .. When a Grails app is created, the project includes a number of localized property files in the grails-app/i18n/ directory The messages.properties file in the grails-app/i18n/ directory contains default validation messages in English. These messages are used when validation fails in a domain class or command object. In addition to the default messages.properties file, this directory has several other properties files that contain the same messages in other languages. For example, “es” is the language code for Spanish, so messages_es.properties contains validation messages in Spanish.
  • 9. I18n Directory Structure Continued .. Example of a properties file - application.properties app.grails.version=2.4.4 app.name=smartly app.servlet.version=3.0 app.version=0.1 Property files are plain text files, which contain name-value pairs.
  • 10. Retrieving Messages // GroovyMessages.groovy def messages = ResourceBundle.getBundle('messages') def appName = messages.getString('app.name') println "application name is ${appName}"
  • 11. Retrieving Messages - message Tag <body> ... <g:message code="app.smartly.welcome"/> ... </body> The code attribute tells the message tag which property value should be retrieved. By default, Grails will decide which version of the property file to use based on the locale of the current web request. A simple way to test your Grails application’s localization is to include a request parameter named lang and assign it a valid language code, such as “es” for Spanish
  • 12. Using URLMapping A URL Mapping for Localization class UrlMappings { static mappings = { "/store/$lang"(controller:'store') // ... } } This mapping will map all requests to a URL such as http://localhost: 8080/smartly/en/ or http://localhost:8080/smartly/es/, where “en” and “es” could be any valid language code.
  • 14. Using Parameterized Messages Often a user message may consist of more than simple static text. The message may need to include some data that is not known until runtime. Defining a Parameterized Message # messages.properties gtunes.purchased.songs=You have purchased ({0}) songs.
  • 15. Continued java.text.MessageFormat class uses a zero-based index {0} in the message is a placeholder for the value of the first parameter. If the message had multiple parameters, they would be represented in the value of the message with placeholders like {0}, {1}, {2}, and so on. The message tag supports an optional parameter named args, and if that parameter is assigned a value, its value will be treated as a list of parameters that need to be applied to the message.
  • 16. Continued gtunes.purchased.songs=You have purchased [{0}] songs <div> <g:message code="gtunes.purchased.songs" args="[97]"/> </div>
  • 18. Using messageSource Grails provides a bean named messageSource that can be injected into any Grails artefact, including controllers, taglibs, other beans, and so on. The messageSource bean is an instance of the org.springframework.context. MessageSource interface This interface defines three overloaded versions of the getMessage method for retrieving messages from the source.
  • 19. Using messageSource Continued .. String getMessage(String code, Object[] args, Locale locale) String getMessage(String code, Object[] args, String defaultMessage, Locale locale) String getMessage(MessageSourceResolvable resolvable, Locale locale) Since the messageSource bean participates in Grails’s dependency autowiring process, all you need to do to get a reference to the bean is declare a property named messageSource in your Grails artefact.
  • 20. Using messageSource Continued .. package com.gtunes class StoreService { def messageSource def someServiceMethod() { def msg = messageSource.getMessage('gtunes.my.music', null, null) // ... } ... } Note that the second and third arguments are null. The second argument is an Object [], which would be used to pass parameters to a parameterized message. The third argument is a java.util.Locale, which may be specified to retrieve a message for any Locale other than the default Locale for this request.
  • 21. Using messageSource Continued .. Example - class StoreService { def messageSource def someServiceMethod() { def msg = messageSource.getMessage('gtunes.my.music',null,Locale.ITALIAN) // … } ... }
  • 22. Using g.message From within a Controller or TagLib artefact, a simpler way to retrieve messages is to invoke the message GSP tag as a method on the special g namespace variable available in those artefacts def index() { def msg = g.message(code:'gtunes.my.music') } //All tag libraries are accessible using the very same technique.
  • 24. Summary Retrieving messages from a property file is a snap in a Grails application. The message tag is very easy to access and use from GSP pages and GSP templates. The messageSource bean is easily accessible from wherever the application may need it. All of these enhancements are built on top of proven and well-understood Java-platform tools, including java.text. MessageFormat and org.springframework.context.MessageSource.