Localize Strings in Javascript

Viewed 52052

I'm currently using .resx files to manage my server side resources for .NET.

the application that I am dealing with also allows developers to plugin JavaScript into various event handlers for client side validation, etc.. What is the best way for me to localize my JavaScript messages and strings?

Ideally, I would like to store the strings in the .resx files to keep them with the rest of the localized resources.

I'm open to suggestions.

12 Answers

A basic JavaScript object is an associative array, so it can easily be used to store key/value pairs. So using JSON, you could create an object for each string to be localized like this:

var localizedStrings={
    confirmMessage:{
        'en/US':'Are you sure?',
        'fr/FR':'Est-ce que vous ĂȘtes certain?',
        ...
    },

    ...
}

Then you could get the locale version of each string like this:

var locale='en/US';
var confirm=localizedStrings['confirmMessage'][locale];

Inspired by SproutCore You can set properties of strings:

'Hello'.fr = 'Bonjour';
'Hello'.es = 'Hola';

and then simply spit out the proper localization based on your locale:

var locale = 'en';
alert( message[locale] );

I would use an object/array notation:

var phrases={};
phrases['fatalError'] ='On no!';

Then you can just swap the JS file, or use an Ajax call to redefine your phrase list.

With a satellite assembly (instead of a resx file) you can enumerate all strings on the server, where you know the language, thus generating a Javascript object with only the strings for the correct language.

Something like this works for us (VB.NET code):

Dim rm As New ResourceManager([resource name], [your assembly])
Dim rs As ResourceSet = 
    rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True)
For Each kvp As DictionaryEntry In rs
    [Write out kvp.Key and kvp.Value]
Next

However, we haven't found a way to do this for .resx files yet, sadly.

JSGettext does an excellent job -- dynamic loading of GNU Gettext .po files using pretty much any language on the backend. Google for "Dynamic Javascript localization with Gettext and PHP" to find a walkthrough for JSGettext with PHP (I'd post the link, but this silly site won't let me, sigh...)

Edit: this should be the link

Expanding on diodeus.myopenid.com's answer: Have your code write out a file containing a JS array with all the required strings, then load the appropriate file/script before the other JS code.

The MSDN way of doing it, basically is:

You create a separate script file for each supported language and culture. In each script file, you include an object in JSON format that contains the localized resources values for that language and culture.

I can't tell you the best solution for your question, but IMHO this is the worst way of doing it. At least now you know how NOT to do it.

Related