我多次遇到同样的问题,翻译必须用 JavaScript 处理。我想出的最佳解决方案是将翻译对象从服务器发送到前端。我给你举个例子
首先创建包含翻译文件的文件夹。比创建另一个文件来处理翻译。它的目的是生成一个 JavaScript 对象,该对象将被发送到前端。在我的例子中,它是一个 PHP 服务器,所以我创建了一个名为 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;
根据您的业务逻辑,在页眉页脚中包含 translation.js.php 文件。就我而言,我只需要翻译使用 JavaScript 动态创建的内容,因此我将其处理为 footer.php 文件
...
<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>
最后是 main.js 文件
console.log(translate)
// how lets set the heading using jQuery
$('h1#main_heading').html(translate.hello_world)