JavaScript based internationalization in Grails
Generally Internationalization is used for displaying HTML text based on user’s locale or region. This is often done on server side of the application.
Of late a lot of applications do the HTML generation on the client side, rather than on the server side. And to support the internationalization on client side is a common problem in this scenario.
Currently there are 2 ways to achieve internationalisation on client side:
1.Pass the i18n messages from controller to client side in response
2.Internationalize the required messages on the client side instead of server side
Both of them are not easy. But, out of the two, I would personally recommend the second option as passing the i18n messages every time in the response is not a good practice.
However, if we are working on Grails framework, the second option is fairly easy to achieve due to its i18n-asset-pipeline plugin.
i18n-asset-pipeline plugin is an asset pipeline plugin, that generates a JavaScript file with internationalized texts, which can be used for client side i18n.
To use this plugin, add the following code to your BuildConfig-
[java]
plugins {
compile ":i18n-asset-pipeline:1.0.6"
}
[/java]
For defining internationalised messages we have to create a special file (per locale) with ‘i18n’ extension, eg. messages_fr.i18n, where ‘_fr’ represents french locale and ‘messages’ is the base name of the file that is common amongst all files. These files contains list of local messages keys you would like to use on the client-side.
Now, to load the messages file for specific locale, all you have to do is use the following tag in your code:
[java]
<asset:i18n locale="en_UK" />
OR
<asset:i18n locale="${locale}" name=”text”/>
[/java]
where locale is a string or locale object and name is the base name of the file you want to load. In first case the “messages_uk.i18n” file will be loaded and in second case, if the locale object is of France then “text_fr.i18n” file will be loaded.
After the file is loaded you can show the locale specific message by using following code:
[java]$L("user.name.label")[/java]
assuming, user.name.label is one of the keys defined in your locale file.
The beauty of this plugin is that it creates a JS file similar to messages.properties and places all the keys and their values, that it had pick from correspoding message.properties file, in it. And since the output file is .js type, therefore now you can use the locale specific messages in your javascript code without worrying about where to get them from.
For further details you can use my sample project.
Hoping this information was helpful. Happy Internationalisation!
Cheers!