April 9, 2020
Estimated Post Reading Time ~

JavaScript based internationalization in Grails

Generally, Internationalisation is used for displaying HTML text based on user’s locale or region. This is often done on the 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 internationalisation 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. Internationalise 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 the Grails framework, the second option is fairly easy to achieve due to its i18n-asset-pipeline plugin.

The i18n-asset-pipeline plugin is an asset pipeline plugin, that generates a JavaScript file with internationalised texts, which can be used for client-side i18n.
To use this plugin, add the following code to your BuildConfig-
plugins {

compile ":i18n-asset-pipeline:1.0.6"

}

For defining internationalized 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 contain a list of local message keys you would like to use on the client-side.
Now, to load the messages file for a specific locale, all you have to do is use the following tag in your code:

<asset:i18n locale="en_UK" />
OR
<asset:i18n locale="${locale}" name=”text”/>


where locale is a string or locale object and name is the base name of the file you want to load. In the first case the “messages_uk.i18n” file will be loaded and in the 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 the following code:

$L("user.name.label")

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 the corresponding 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!



By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.