What Are The Different Approaches To Multilingual Javascript Applications
Solution 1:
You can simply make a big object tree:
var languages = {
english:{
Save:"Save"
},
german:{
Save:"Speichern"
}
};
In your app:
var l = languages.german;
alert(l.Save); //Alerts "Speicher"
The benefit of this system is that you can make sub objects to group some values together.
Solution 2:
Whatever you do, the most important thing is to separate between your code and the texts.
If the code and the texts are mixed, maintenance will be impossible and you'll soon abandon it.
The translatable texts must be easily scanned, so that translators can translate just texts. Then, you should be able to insert the translations conveniently.
We use a JS file that includes a map of strings. We have a simple Python script that extracts the translatable strings from it. The same script also builds the output JS file that includes the same labels with the translated strings.
The result is:
- When the application evolves, it's easy to add new strings.
- The script automatically finds the new strings and we can translate them.
- Completed translations go back to the JS file without manual work.
Solution 3:
I like using a "language dictionary array", which you can do using JSON or a simple array.
This is easy to implement:
var lang = 0//0 = english, 1=frenchvar phrases=[]
phrases['cancel'] = "cancel,annuler".split(",")
alert(phrases['cancel'][lang])
Solution 4:
Here's a function I put together to handle language translations based on the accepted answer in this question:
/**
Core script to handle language translations
**/varLanguage = function() {
var activeLanguage = 'en';
var languagePack = {
'en': {
'hello-world': 'Hello World',
'show-variants': 'Show Variants',
'hide-variants': 'Hide Variants'
},
'fr': {
'hello-world': 'Bonjour World',
'show-variants': 'représentent des variantes',
'hide-variants': 'masquer variantes'
}
}
var translate = function(key, language)
{
if (typeof languagePack[language] == 'undefined')
{
return;
}else {
return languagePack[language][key];
}
};
return {
init: function(language)
{
activeLanguage = language;
},
getString: function(key, defaultText)
{
var text = translate(key, activeLanguage);
if (typeof(text) === 'undefined' || text.length == 0 || text == null)
{
text = defaultText;
}
return text;
}
}
}();
Then to initialise it in common page code, where ${language.language}
is jsp code to set the language from a server side configuration.
<scripttype="text/javascript">jQuery(document).ready(function() {
Language.init('${language.language}');
});
</script>
Then whenever you need a message use
Language.getString('hello-world', 'Hi World');
Post a Comment for "What Are The Different Approaches To Multilingual Javascript Applications"