Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice javascript and multilanguage

what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea?

like image 806
marquies Avatar asked Oct 23 '08 07:10

marquies


People also ask

How do you use localization in Javascript?

To perform file-based localization, we need to extract this content into a file, possibly in JSON format, and then retrieve it from the file. Let's make a file in a language folder to keep track of all files for different languages: ```JSON <! -- ./lang/en.

How do I serve a page with contents in multiple languages?

To change the language, just simply set the lang attribute. We can define it anywhere in the document, such as in the body, in the paragraph, in the heading, or in the span tag. But the best practice is to set the lang in the span tag.


1 Answers

When I've built multi-lingual sites before (not very large ones, so this might not scale too well), I keep a series of "language" files:

  • lang.en.js
  • lang.it.js
  • lang.fr.js

Each of the files declares an object which is basically just a map from key word to language phrase:

// lang.en.js lang = {     greeting : "Hello" };  // lang.fr.js lang = {     greeting : "Bonjour" }; 

Dynamically load one of those files and then all you need to do is reference the key from your map:

document.onload = function() {     alert(lang.greeting); }; 

There are, of course, many other ways to do this, and many ways to do this style but better: encapsulating it all into a function so that a missing phrase from your "dictionary" can be handled gracefully, or even do the whole thing using OOP, and let it manage the dynamic including of the files, it could perhaps even draw language selectors for you, etc.

var l = new Language('en'); l.get('greeting'); 
like image 146
nickf Avatar answered Oct 20 '22 14:10

nickf