29 SEPTEMBER 2009
During AJAX requests or when toggling the state of interface elements, JavaScript may be used to display messages to the User. The translate function provides an easy way to translate these messages.
Any JavaScript code that needed to use a string would reference the LOCALIZATION object rather then embedding a string:
You can pass a string with an "%s" inside which can be used for string substitution.
LOCALIZATION.WARNING: 'Achtung vor dem %s, er ist gefährlich !'
alert(translate(LOCALIZATION.WARNING, "Zauberer"));
localization.[de|en|fr|...].jsIf you use the LOCALIZATION Object throughout your code, you need only to change the Strings in the localization file.
The german localization file could look like this:
localization.de.js
// Example
var LOCALIZATION = {
LANGUAGE: 'GERMAN',
WARNING: 'Achtung vor dem %s, er ist gefährlich !',
LOADING: 'Bitte warten, Daten werden geladen',
WELCOME: 'Hallo %s, wie geht\'s dir ?'
};
Make sure that this file is loaded before any other file, which uses the localization.
translate.js
(function () {
if (!window.translate) {
/**
* this global function is for string substitution
* @property {string} string to translate.
* @property {string} as much
* return STRING
*/
window.translate = function(){
var html = [ ];
var arguments = arguments;
var string = arguments[0];
var objIndex = 0;
var reg = /%s/;
var parts = [ ];
/**
* analyze the string, extract the parts with the %s identifier.
*/
for ( var m = reg.exec(string); m; m = reg.exec(string) ) {
// m[0][0] gives undefined in IE
parts.push(string.substr(0, m[0][0] === "%" ? m.index : m.index));
parts.push("%s");
string = string.substr( m.index+m[0].length );
}
parts.push(string);
/**
* analyze the parts, replace the %s with the given arguments.
* beware of undefined!
*/
for (var i = 0; i < parts.length; ++i){
var part = parts[i];
if (part && part == "%s"){
var object = arguments[++objIndex];
if (object == undefined) {
html.push("%s");
}else{
html.push(object);
};
}else{
html.push(part);
}
}
/**
* Join the array and return as string.
*/
return html.join('');
}
};
})();
You can find a test page here and the translate.js file here.
The code is inspired by the firebug function and the PHP printf function.
Magento powered fabric store for organic cotton
Mass Customization Fashion Label from Germany
Blog- and Community site for the first Game-TV-Show on MTV Germany.
MTV Home is one of MTV Microsite's wich runs on the new developed Rails-Microsite-Engine at MTV Germany.
Game-Based Learning Platform for kids.
Modéliste . Creative Pattern Cutter
Rails Programmer
Rails Programmer