I currently have a languages.js set up as such:

var MaterialProperties = 0;
var YieldStrength = 1;
var OtherPhrases = 2;

//continue to list other phrases - there are 40+

var English = [
    "Material Properties",
    "Yield Strength",
    "Other Phrases"

var Chinese = [
    // Chinese string that means "Material Properties",
    // Chinese string that means "Yield Strength",
    // Other phrases in Chinese

var SelectedLanguage = English; //default

Then I have the user select via dropdown box the language they would like, calling setLanguage(selected_language), which sets SelectedLanguage to either "English" or "Chinese", depending on the value of the dropbox selection.

Everywhere in my HTML where it should read "Material Strength" (or corresponding string in Chinese), I reference this as SelectedLanguage[MaterialProperties], which is the same as saying English[0] or Chinese[0], which returns the correct string.

Is there a better, more efficient, cleaner way to do this?


Try check this library http://www.localeplanet.com/

Everywhere you display text, put into _() function.

For example:

console.log(_('Hello, world!'));

Use the po2js or po2json scripts to convert the .po files to something usable by JavaScript. Put these files on your website and add the appropriate one to your pages.

| improve this answer | |
  • \$\begingroup\$ How does localeplanet know which language to use from the json file? I don't see anything in the documentation regarding this \$\endgroup\$ – Jaken Herman Apr 11 '17 at 19:15
  • \$\begingroup\$ Propably use in javascript something like this var userLang = navigator.language || navigator.userLanguage; userLang is the browser language... \$\endgroup\$ – Mikołaj Osowski Apr 15 '17 at 13:13

Typically localization might be achieved through storing localization in configuration files (perhaps in JSON) which would be deployed along with the application. The appropriate config would be loaded into memory based on localization setting such that main app code code just references a string identifier.

This would be in contrast to your approach of loading all translations into javascript variables in memory, which could get memory intensive if you have a large number of strings.

So you might take a look at a plug-in like this which takes this general approach.

| improve this answer | |

Not the answer you're looking for? Browse other questions tagged or ask your own question.