I wonder what are the different and which is the best method to set up some multilingual javascript application. i want to have all used strings in one file to e开发者_如何学Pythonasily change strings or add more languages later.
thnx!
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.
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.
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=french
var phrases=[]
phrases['cancel'] = "cancel,annuler".split(",")
alert(phrases['cancel'][lang])
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
**/
var Language = 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.
<script type="text/javascript">
jQuery(document).ready(function() {
Language.init('${language.language}');
});
</script>
Then whenever you need a message use
Language.getString('hello-world', 'Hi World');
精彩评论