Each company’s business is different. This solution is for reference only.

Git demo address

preface

There are actually three common solutions for multilingual developers:

The first is to provide relevant pages for each language for each page. The second is to separate content from presentation and make content files in different languages. The third is dynamic translation of page content. The third is rare, and machine translation has struggled to live up to expectations.

Actually, the second one is a little bit easier. Let’s do it.

implementation

thinking

  • Some excel files and some JSON files are provided by the translation company. Let’s uniformly request JSON files.
  • Add a tag to the HTMLlangProperty to iterate through all of these when the page loadslangAttribute tag to achieve switching language;
  • Js text with methods to achieve conversion language;
  • Save the user’s chosen language into a cookie, eh! Take a little notebook and write it down;
  • Do a cache, requested language files are no longer requested;
  • That’s all for now…

demo

File directory

index.html


      
<html>
<meta charset="utf-8">  
<title>translation test</title>  
<script src="https://cdn.bootcss.com/jquery/1.11.0/jquery.min.js"></script>
<script src="js/script.js"></script>  
<script src="js/index.js"></script>  
</head>  
  
<body>  
    <div>  
        <a href="#" id="enBtn">English</a>  
        <a href="#" id="zhBtn">Simplified Chinese</a>  
    </div>  
    <div><a lang>click here:</a></div>  
    <div><input type="button" value="apply" lang id="applyBtn"></div> 
</body>  
  
</html>  

Copy the code

script.js

var dict = {};

$(function () {
  registerWords();
  if(getCookieVal("lang") = ="en"){
    setLanguage("en");
  }else if(getCookieVal("lang") = ="zh"){
    setLanguage("zh");
  }else{
    setLanguage("en");
  }
  
// The language switch event depends on your business
  $("#enBtn").bind("click".function () {
    setLanguage("en");
    // You can also write other operations here, such as loading the CSS for the language
  });

  $("#zhBtn").bind("click".function () {
    setLanguage("zh");
  });

});

function setLanguage(lang) {
  setCookie("lang=" + lang + "; path=/;");
  translate(lang);
}

function getCookieVal(name) {
  var items = document.cookie.split(";");
  for (var i in items) {
    var cookie = $.trim(items[i]);
    var eqIdx = cookie.indexOf("=");
    var key = cookie.substring(0, eqIdx);
    if (name == $.trim(key)) {
      return $.trim(cookie.substring(eqIdx + 1)); }}return null;
}

function setCookie(cookie) {
  var Days = 30; // This cookie will be kept for 30 days
  var exp = new Date(a);//new Date("December 31, 9998");
  exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
  document.cookie = cookie+ "; expires=" + exp.toGMTString();
}

function translate(lang) {
  if(sessionStorage.getItem(lang + "Data") != null){
    dict = JSON.parse(sessionStorage.getItem(lang + "Data"));
  }else{
    loadDict();
  }

  $("[lang]").each(function () {
    switch (this.tagName.toLowerCase()) {
      case "input":
        $(this).val(__tr($(this).attr("lang")));
        break;
      default:
        $(this).text(__tr($(this).attr("lang"))); }}); }function __tr(src) {
  return (dict[src] || src);
}

function loadDict() {
  var lang = (getCookieVal("lang") | |"en");
  $.ajax({
    async: false.type: "GET".url: "/lang/"+lang + ".json".success: function (msg) {
      dict = msg;
      sessionStorage.setItem(lang + 'Data'.JSON.stringify(dict)); }}); }// Iterate over all lang attribute tag assignments
function registerWords() {$("[lang]").each(function () {
    switch (this.tagName.toLowerCase()) {
      case "input":
        if($(this).attr("lang") = =""){
          $(this).attr("lang", $(this).val());
        }
        break;
      default:
        if($(this).attr("lang") = =""){
          $(this).attr("lang", $(this).text()); }}}); }Copy the code

Back in the demo, the registerWords function was not evaluated here but our project wrapped its own route to dynamically load the page. It reassigns every time it comes in, which can cause problems.

Because it assigns the value of the current element, the value of your lang does not correspond to the key in the language package file

Method of use

Language switch in HTML: add lang attribute to all tags. Language switch in JS: use __tr() method

You can use script.js directly as a plug-in and put it into your project

conclusion

All roads lead to Rome, just do it according to your actual needs and business scenario.

Have a bit hasty, have inadequacy still ask everybody to give directions.