Multi-language HTML5 application
Asked Answered
B

2

7

I'm developing a HTML5 application with CSS3 and jQuery.

I have some text that I want to show in user language. Do you know how I can do that?

This application will run on Blackberry Playbook and on others mobile devices.

I don't know how to get user OS language, or where I must put my localize strings, etc.

Any clue?

Buxom answered 2/3, 2012 at 14:51 Comment(0)
S
4

I store my localized string in JS files (1 for each supported language). Ex. :

string-en.js :

 MyApp.STR = {"Hi":"Hi","By":"By", etc.};

string-fr.js :

 MyApp.STR = {"Hi":"Salut","By":"Par", etc.};

And at startup, I load the right file regarding the language of the navigator :

 loadLocalizedString: function(langParam/*optional*/) {
    var language = window.navigator.language, lang; 
    console.log('loadLocalizedString with Navigator Language: ' + language);
    if (!langParam) {
        //Try to guess the best suited language
        if(language) {
             lang = language.substring(0,2); 
        } else {
             lang = 'en';
        }
        if($.inArray(lang, this.SUPPORTED_LANGUAGE) <= -1) {
            lang = 'en';//If the language is not available : english by default
        }
    } else {
        lang = langParam;
    }

    console.log('language: ' + lang);

    this.loadString('lib/string-'+lang+'.js');
},
    SUPPORTED_LANGUAGE : ["en", "fr", "es", "it"],
loadString:function(fileName) {
    try {
        $.ajaxSetup({async: false});
        $.getScript(fileName);//We don't use the async callback, because we need the translation in the next method
        $.ajaxSetup({async: true});

    } catch (e) {
        console.error('Error while loading : ' + fileName);
    }

}

And to use the localized string in the app :

   html = MyApp.STR.Hi+' '+userName+' !';
Southeasterly answered 2/3, 2012 at 17:10 Comment(1)
if it was a phrase instead of a word, how could we call the object key?Ader
E
0

I would suggest trying to detect the browser language using Javascript. I don't see a direct way to detect it using HTML.

Here is a link that addresses the issue:

Is there anyway to detect OS language using javascript?

Epley answered 2/3, 2012 at 16:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.