In a previous post I mentioned a few ways of dealing with i18n of strings in ASP.NET pages with gettext. Now it’s time for javascript code.

Although javascript code in ASP.NET pages can be internationalized using the <%= %> syntax, pure js files are not processed, and therefore a different mechanism for dealing with javascript is needed.

A quick google search will return multiple results. BerliOS javascript gettext implementation provides an interface with the same methods as the ones provided by any other port. It requires that the content of the translation files is available as a dictionary visible to the script.

Note that it is not necessary to have a full implementation of gettext client side. Having a simple function for translation, checking a simple dictionary will do:

Resources.T = function(str) { return Resources[str] || str };"

The Resources dictionary can be easily passed to the client via JSON, by retrieving the full dictionary on the server and encoding it.

An efficient approach for including this data is having a server endpoint returning this dictionary as json and including it as a referenced script in all master pages. This will cause the browser to download the full set of resources the first time and then used it cached version; therefore it is not necessary to send the full load of strings on every request. Make sure to add the culture of the requested resource to the URL, so when a user changes his/her language the new resource set is loaded.

As for .po generation, xgettext seems to crawl javascript code without too many issues, so this point should not pose any problems.

On the other hand, the gettext-js library provides client side methods for parsing .po files. Therefore, it is not necessary to add a server endpoint with the intelligence to convert the po file into its json representation: the library will take care of this by itself, just point itself to an URL containing the file to parse and voila!

Note, however, that since the po file may have some metadata which is used only during translation time (such as in which files is the string referenced, the format, etc), its size may actually double or triple its json representation, making it more expensive to be sent to the client.

Also, conversion of the .po files into json can be done a single time in the server and sent to every client, instead of having each of them spend extra browser processing time parsing and processing.

Either approach you take, gettext remains an excellent tool for internationalizing your web application.