【问题标题】:How to handle translation for texts inside a .js of a WP theme如何处理 WP 主题的 .js 中的文本翻译
【发布时间】:2017-09-21 05:28:09
【问题描述】:

我有一个 wordpress 应用程序,当我需要回显需要翻译的内容时,我通常使用 PHP 函数 <?php _e('foo', 'bar') ?>。但是,现在我正在实现一个新功能,在我的 .js 文件中我有类似

var confirmation = confirm("Are you sure you want to quit"); 
if(confirmation){
 ... 
}

上面代码的问题是我不能使用PHP函数_e()来翻译它,因为这是一个JS脚本。

有没有办法为 JS 中回显的文本启用翻译?

赏金之后

我正在悬赏,因为给出的问题是通用的,而我正在寻找可以解决我的问题的解决方案。

我正在从事以前由某人构建的 WP 项目。我应该只对存在于名为 functions.js 路径的 js 文件中的代码添加翻译:C:\Users\meskerem\foo.com\wp-content\themes\foo\assets\scripts\functions.js 假设函数内部存在以下代码。

var confirmation = confirm("Are you sure you want to quit"); 
if(confirmation){
 ... 
}

现在的目标是使英语句子可翻译。上面的 js 代码是在点击该文件内的按钮时执行的。 C:\Users\meskerem\foo.com\wp-content\plugins\wp-jobhunt\templates\dashboards\candidate\templates_ajax_functions.php

触发翻译的html代码很简单:

<h1> <?= _e('good morning', 'jobhunt') ?> </h1>
<div> <i class='icon-trash' onclick="askConfirmation()"> x </i> </div>

所以,脚本很简单,但翻译是我遇到的一些问题。

【问题讨论】:

  • 您的 confirm("text") 应该在 if 语句 (if(confirm("text")) { /*code*/ }) 内。剩下的我无能为力,因为我几乎没有 wordpress 知识。
  • @Pyromonk 否,否则永远不会触发 if 语句。
  • @Pyromonk 啊,您的消息在“if 语句内部”中读取,意思是如果满足“if”条件。而你的意思是让它成为条款本身的一部分。例如if(confirm){var confirmation = confirm("Are you sure you want to quit"); }
  • 对不起,我是想说if(confirmation){}
  • 没有问题@Pyromonk 一个小提琴总是有利于清理事情。

标签: javascript php wordpress


【解决方案1】:

在 word press 中,您必须将翻译数组传递给相应的 java 脚本。

例如,

如果您在 function.php 文件中排队脚本,如下所示,

wp_enqueue_script( $handle, $src, $deps,$ver,$in_footer );

你必须通过在 wp_localize_script() 中使用他的句柄来添加从函数文件到特定 js 的翻译;

  e.g. wp_enqueue_script( 'your-handle', $src, $deps,$ver,$in_footer );

  $translation_array = array('messagekey' => __('Are you sure you want to quit', foo');                             );
  wp_localize_script('your-handle', 'langvars', $translation_array);

你的情况

wp_enqueue_script( 'cs_functions_js', plugins_url('/assets/scripts/functions.js', __FILE__ ), '', '', true );

just add below code after above code.

$translation_array = array('messagekey' => __('Are you sure you want to quit', foo');                                );
  wp_localize_script('cs_functions_js', 'langvars', $translation_array);

然后就可以用js访问翻译了,

var confirmboxmessage = langvars.messagekey;
var confirmation = confirm(langvars.messagekey);

【讨论】:

【解决方案2】:

您应该使用 wp_localize_script 函数,正是出于这个原因,该函数被添加到 WordPress 中。

试试这样的:

wp_localize_script( $handle, $name, $data );

例子

<?php

// Register the script
wp_register_script( 'some_handle', '<ENTER YOUR SCRIPT PATH HERE>' );

// Localize the script with new data
$translation_array = array(
    'some_string' => __( 'Some string to translate', 'plugin-domain' ),
    'a_value' => '10'
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );

// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );

您可以按如下方式访问 JavaScript 中的变量:

<script>
// alerts 'Some string to translate'
alert( object_name.some_string);
</script> 

注意:生成的 JavaScript 调用中的数据将作为文本传递。如果您尝试传递整数,则需要调用 JavaScript parseInt() 函数。

<script>
// Call a function that needs an int.
FinalZoom = map.getBoundsZoomLevel( bounds ) - parseInt( object_name.a_value, 10 ); 
</script>

【讨论】:

  • 我需要在我的应用程序中添加path/to/myscript.js 文件,还是可以使用我已有的文件?
  • 不,您使用文件的路径。给出的只是一个示例,表明您需要使用自己的路径。请接受我的回答,因为这是做你需要的正确方法。请参阅我发布到 WordPress codex 的链接以进行确认。
  • 您能否更新您的答案,以便我接受并投票?目前它对我不起作用
  • 顺便说一句:你说的那部分"// Register the script wp_register_script( 'some_handle', 'path/to/myscript.js' );" 我确定myscript.js 已经注册了。它是 jobhunt 插件的一部分,在我决定向其中添加一个小功能之前,已经有大量脚本在运行。那么,我还需要添加这个吗?
  • 附言。我的答案是正确的,我没有必要详细说明在特定情况下您应该如何做某事。这是你自己想办法,但我正在尽我最大的努力,并将在合理的范围内继续这样做。
【解决方案3】:

如果我对问题的理解正确,您有一个脚本被第三方插件或主题加入队列,并且您希望在不修改原始脚本的情况下本地化 window.confirm 框。

/wp-content/plugins/jobhunt-client-translations/jobhunt-client-translations.php

<?php
/*
Plugin Name: Jobhunt Translations
Author: John Doe
*/

add_action( 'wp_enqueue_scripts', function() {

    wp_enqueue_script( 'translations', plugins_url( '/translations.js', __FILE__ ) );

    // change the translations domain from 'default' to match yours
    // you can also add other translations here in format "message" => "translated message"
    wp_localize_script( 'translations', 'DialogMessages', [ 'Are you sure you want to quit' => __( 'Are you sure you want to quit', 'default' ) ] );

});

/wp-content/plugins/jobhunt-client-translations/translations.js

(function( original ) {
    window.confirm = function( message ) {
        message = DialogMessages[message] || message;
        return original.call( this, message );
    };
})(window.confirm);

/wp-content/plugins/目录下新建文件夹jobhunt-client-translations,放入这两个文件,激活插件。 它将简单地覆盖默认的window.confirm 对话框,而不更改任何原始的第三方文件,并且不会修改对话框的默认行为,除非该消息将被翻译。

代码已经过测试,可以正常运行。

【讨论】:

    【解决方案4】:

    也许这会有所帮助

    function addScript() {
        wp_enqueue_script( 'functions', get_template_directory_uri() . 'foo\assets\scripts\functions.js', array(), '1.0.0', true );
    }
    add_action( 'wp_enqueue_scripts', 'addScript' );
    

    【讨论】:

      【解决方案5】:

      制作一个简单的 PHP 脚本,您的 JS 可以通过 AJAX 调用它,它只不过是翻译一个字符串(或多个字符串),通过 HTTP GET 发送并将其作为响应正文回显(可能使用 json_encode())。

      然后你可以创建一个 JS 函数来进行 AJAX 调用,所以调用它可以像调用 JS 函数一样简单

      var confirmTxt = jstranslate('Are you sure you want to quit?');
      

      并以 JQuery 为例:

      function jstranslate(string)
      {
          translations = $.get('/my-ajax-translate-url',{string: string}, function(e){
              return e.text; // console.log e to double check what to return, this is from memory
          });
      }
      

      在 PHP 中

      // require_once() your _e() function.
      $text = _e($_GET['string'], 'jobhunt');
      header('Content-Type: application/json');
      echo json_encode(array('text' => $text));
      exit;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-08
        • 2017-01-07
        • 2020-04-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多