MultiLanguage Support for Vanilla Javascript application

Viewed 23

I have a Web Applicaiton written in Pure Javascript. We are doing lot of DOM manipulations using jQuery.

We are not using any third party packages and not even Node JS and want to have this app in simple pure Javascript.

During the development we have hardcoded many String directly in the HTML like below

 <div id='empName' class="empClass">Employee Name</div>

 <div id='depName' class="depClass">Dep Name</div>

Most of the app contains like above.

We are now looking for a way to support it for MultiLanguage, How can I convert my existing app to support multilanguage.

Below is the approach I am thinking of

  • I did my research and planning to construct a JSON file for each language,
  • Have seperate CSS file for each language and load dynamically

Is the above approach correct ?

How can I do the interpolation here like in the DIV InnerHTML I want to give the json Object value ? How could this be done

The html files are in separate View folder and how could I place the json object values to the elements in html files

1 Answers

create a language sentence array, and use indexing and grouping by local under each key

const langauge = (key, local) => {
  const sentances = {
      "hello" : {
        "en": "Hello",
        "fr": "bonjour",
      }
  }
  return sentances[key][local] || "";
}

the you could do this in js

let local = "en";
let hello = langauge("hello", local);

or in html inline

 <div id='empName' class="empClass"><script>document.write(langauge("hello", "en"))</script></div>

example usage

const langauge = (key, local) => {
  const sentances = {
      "hello" : {
        "en": "Hello",
        "fr": "bonjour",
      }
  }
  return sentances[key][local] || "";
}

let hello_en = langauge("hello", "en");
let hello_fr = langauge("hello", "fr");

console.log(hello_en, hello_fr);

enter image description here

Test online

you may test here

Related