Multi language page with Javascript or jquery

僤鯓⒐⒋嵵緔 提交于 2019-12-01 07:41:25

问题


Currently I am working on web app that will support several languages. Therefore I prepared table in my database with translations. However, I am not sure how to populate web app with translations. The easiest way, in my opinion, is to put reference to appropriate translation in each element of the page. This would work great in PHP I don't know how to make it work in js or JQuery.

What I would like to have is the reference to array in divs like this:

    <div> {translation_array['login']} </div>

So that the div would "take" value from translation_array, but I lack the knowledge to do it. Is it possible to make it work this way?

If not, I would appreciate advices on how to make multilanguage web in js.

thanks


回答1:


Use on every piece of text you want to change according to the language a span HTML tag because you can embed inline on every piece of HTML (contrary to div or p which have a display:block by default). Then for each span use a class with a name starting with a certain pattern, for example:

<span class="lang-text1"></span>

Then using jQuery's function .each change every span tag that matches the pattern lang in its class name, according to the selected language.

I put also here a simple example for you to check.

var LanguageList = {
  "EN" : "English",
  "ES" : "Español",
  "PT" : "Português"
};

//languages Objects
var WORDS_EN = {
  "text1" : "text One",
  "text2" : "text Two"
};

var WORDS_ES = {
  "text1" : "texto Un",
  "text2" : "texto Dos"
};

var WORDS_PT = {
  "text1" : "texto Um",
  "text2" : "texto Dois"
};


window.onload = initialize;

function initialize() {

  var $dropdown = $("#country_select");    
  $.each(LanguageList, function(key, value) {
    $dropdown.
      append($("<option/>").
      val(key).
      text(value));
    });
    
  loadsLanguage("EN");
}

function loadsLanguage(lang){
  /*fills all the span tags with class=lang pattern*/ 
  $('span[class^="lang"]').each(function(){
    var LangVar = (this.className).replace('lang-','');
    var Text = window["WORDS_"+lang][LangVar];
    $(this).text(Text);        
  });
}
div{
  margin: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="country_select" onchange="loadsLanguage(this.value);">
</select>

<div>
  <span class="lang-text1"></span>
</div>
<div>
  <span class="lang-text2"></span>
</div>
<div>
  <span class="lang-text2"></span>/<span class="lang-text2"></span>
</div>



回答2:


Below is a very simple example using jquery and json:

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    <script>

        let arrLang = {
            en: {
                'home' : 'Home',
                'about' : 'About Us',
                'contact' : 'Contact US'
            },

            es: {
                'home' : 'casa',
                'about' : 'sobre nosotros',
                'contact' : 'Contáctenos'
            }
        }

    $(function() {
        let lang =localStorage.getItem('language');
        changeLanguage(lang);


     $('.translate').click(function(){
         lang = $(this).attr('id');
         localStorage.setItem('language', lang);
         changeLanguage(lang);
     });

    function changeLanguage(lang){
        $('.lang').each(function(index,element){
             $(this).text(arrLang[lang][$(this).attr('key')]);
         }); 
    }

    })

    </script>

</head>


<body>

        <button class="translate" id="en">English</button> 
        <button class="translate" id="es">Spanish</button>

        <ul>
            <li class="lang" key="home"> Home </li>
            <li class="lang" key="about"> About Us </li>
            <li class="lang" key="contact"> Contact Us </li>
        </ul>


</body>




回答3:


I have faced the same problem many times where the translation has to be handled with JavaScript. The best solution I came up with is to send translation object from the server to the front-end. I will give you an example

First create folder with translation files. Than create another file where you can handle the translation. It purpose is to generate a JavaScript object which will be send to the front-end. In my case it was a PHP server so I created a file named translation.js.php

/languages/en.php

<?php
$_GET['FILTER'] = [
    "hello_world" => "Hello World",
    "result" => "result",
    "all" => "all",
    "brand" => "brand"
];

/languages/bg.php

<?php
$_GET['FILTER'] = [
    "hello_world" => "Здравей Свят!",
    "result" => "ресултати",
    "all" => "всички",
    "brand" => "марки"
];

/translation.js.php

<?php
// define the posibile languages you can have
$languages = array('en', 'bg', 'fr', 'es');

//set the language from $_GET parameter or any other technique to set the lang
$client_lang = $_GET['lang']; //I am not sure if this parameter has to be escaped

//check if you have the requested language
if(in_array($client_lang, $languages) {
     require_once "languages/" . $client_lang . ".php";
} else { //if the client language is not in languages array, set the default language
     require_once "languages/en.php";
}

$translation = <<<EOT
var translate = {
    hello_world: "{$_GET['FILTER']['hello_world']}",
    results: "{$_GET['FILTER']['results']}",
    all: "{$_GET['FILTER']['all']}",
    brand: "{$_GET['FILTER']['brand']}"
}
EOT;


echo $translation;

Than in your header of footer include the translation.js.php file depending on your business logic. In my case I needed to translate only content which was dynamically create with JavaScript so I handled it the the footer.php file

...
<script><?php require_once "translation.js.php" ?></script>
<!-- then include your main js file which will assume that the translation object exists -->
<script src="<?php echo PATH_R ?>views/assets/js/main.js"></script>

And last you main.js file

console.log(translate)
// how lets set the heading using jQuery
$('h1#main_heading').html(translate.hello_world)


来源:https://stackoverflow.com/questions/40430462/multi-language-page-with-javascript-or-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!