Multi language page with Javascript or jquery

前端 未结 3 1450
臣服心动
臣服心动 2021-01-03 07:53

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 we

相关标签:
3条回答
  • 2021-01-03 08:22

    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)
    
    0 讨论(0)
  • 2021-01-03 08:31

    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>

    0 讨论(0)
  • 2021-01-03 08:39

    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>
    

    0 讨论(0)
提交回复
热议问题