Multilanguage in JavaScript

The problem is to provide methods and necessary data for JavaScript to be able to translate Strings which are shown on the page into different languages. Considering the webdesigner shouldnt have too much work to implement it, the function should be easy to use.
1 answer

Easy to use Multilanguage system for JavaScript

My basic idea on this problem was, to make a similar handling than it is done for multilanguage on serverside. So basically what we need is a file which contains the translations for constants which should be accessible for javascript.

I then created following JavaScript file named "translation.js", which contains the constants for the specific languages and a function which will retrieve them and return a translated String for the constant.


var ML_en_US = [];
ML_en_US['SPACE_PROVIDING']= 'Space providing';
ML_en_US['DEFENSE_STRENGTH']= 'Shieldstrength';
ML_en_US['RESS_STORAGE']= 'Ressource-Storage';
ML_en_US['RESSOURCE']= 'Ressource';
var ML_de_DE = [];
ML_de_DE['SPACE_PROVIDING']= 'Platz';
ML_de_DE['DEFENSE_STRENGTH']= 'Verteidigungsstärke';
ML_de_DE['RESS_STORAGE']= 'Rohstoffkap.';
ML_de_DE['RESSOURCE']= 'Rohstoff';
function ML(tag, language){
try {
var result = eval('ML_' + language + '["' + tag + '"]');
if (result == undefined) return "e:"+tag;return result;}
catch (err) {
return "e:"+tag
}
}

Now arrays can be defined, which have the respective language code in their variable name, and the index is the constant used for translation. By an "eval" command the script looks for the translated version. If there is no translation available the script will catch the error and put "e:" in front of the constant and return that, so it is clearly visible to the designer, that there is no translation available for the constant at the moment.