Wednesday, March 26, 2008

Dynamic messaging and i18n in Grails

When using Grails for internationalization (i18n), you sometimes want to send some dynamic data to insert into the string. For instance, you don't just want to say "User not found.", you want to say "Keith Cochran not found.". So, to do that, you need to pass that information at runtime. Here's how to do that.

In your messages.properties file, add an {x} where you want your dynamic parameters to go. Number them starting at 0. For instance, define user.not.found in messages.properties like this:

user.not.found={0} {1} not found

Now, when you call up that particular string from a controller, pass in the variables you want to display at runtime:

flash.message = message(code: "user.not.found",
args: [user.firstname, user.lastname])


This makes your messaging back to the user much more informative.

-Keith