I use JQuery in my web app and I am wondering what the best way to handle multilanguage in that context is.
I was thinking of creating a file like:
label["login"]["fr"]="Connection"
label["login"]["en"]="Login"
Once the file is loaded I will then do (for each label) a:
$('#login').text(label["login"][selected_language]);
In HTML I would then use:
<a href="login.html"><span id="login"></span></a>
Is this a correct way to do ?
salut luc.
I think the best way is to do it in some kind of backend :P But since you ask for a jQuery version i would use the most used language in the HTML and replace it by the other(s). I would do it like this:
Demo here: http://jsfiddle.net/mHAHz/1/ (click on fr or de to change the language)
I guess i would be to lazy to maintain those objects with the language, so i would just use a language class on the elements i want to translate... (as i have done it here: http://alainbenoit.com/)
I think it would be better you use class and a invented attributed instead of id to control multi-language, because if you have the same text twice in the same page id would broken it because it is unique.
You can try this approach:
Everything that is multi-language text has to have class="is_ml" and ml_label="label" where label could be "login", for example. Did you got my approach?
It would be correct if you closed your
<span>
tag :-) You could also just give the<a>
the appropriate "id" value.A scheme like this would work for a very small site, but once you have many pages, many forms, and many messages, it's going to be really hard to keep track of the messages. You probably will want to look into a templating solution so that you can incorporated data into internationalized messages (amounts, dates, etc).
Of course, there's the problem that viewers who've disabled JavaScript will only get the server-supplied default language.
I like Bernardo Mendes approach (answer #6), however since the sub-objects need to be initialize is better to switch the ml_label and language fields around to minimize the number of sub-objects that have to be initialize to only one per language.
Javascript:
HTML: