te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>Multi language page with Javascript or jquery - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Multi language page with Javascript or jquery - Stack Overflow

programmeradmin3浏览0评论

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

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

Share Improve this question asked Nov 4, 2016 at 19:30 user1857756user1857756 3853 gold badges4 silver badges14 bronze badges 8
  • Check this – aring Commented Nov 4, 2016 at 19:33
  • Since you are saying that you don't want to use a server-side approach (which is probably the best approach), you would probably be best served by just having the various pages, pre-written in the various languages and based on a user selection redirect to a pre-made page. – Scott Marcus Commented Nov 4, 2016 at 19:33
  • Probably easiest to acplish using a library like Vue.js or Angular, you could bind the elements to aspects of a model, which would be your set of strings for displaying that region. When the user changes the active language, you update the model and the library paints the new values into the view. – Chris Baker Commented Nov 4, 2016 at 19:33
  • check this stackoverflow./questions/40176555/… – Mamdouh Saeed Commented Nov 4, 2016 at 19:34
  • I feel you got everything you need. On language change just call the javascript function which will load values from prefetched data structure preferrably JSON array and assign it to elements. $("#longin").text(jsonelement); and so on. Assign ids to elements on page. And on page load fetch all information from server in JSON array object each node to represent language and sub elements for id and value for that element. – pratikpawar Commented Nov 4, 2016 at 19:39
 |  Show 3 more ments

3 Answers 3

Reset to default 10

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./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>

Below is a very simple example using jquery and json:

    <script src="https://ajax.googleapis./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>

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)

  1. 暂无评论