如何处理WP主题.js内文本的翻译

2022-08-30 18:34:24

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

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

上述代码的问题在于,由于这是一个JS脚本,因此我无法使用PHP函数来翻译它。_e()

是否无论如何都可以为JS中回显的文本启用翻译?

赏金之后

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

我正在研究以前由某人构建的WP项目。我应该只向js文件中存在的代码添加一个翻译,称为path:让我们假设函数内部存在以下代码。functions.jsC:\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>

所以,脚本很简单,但翻译是我有一些问题的地方。


答案 1

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

例如

如果你是 en 队列脚本,如下所示从函数.php文件,

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

你必须通过使用他在wp_localize_script()中的句柄将转换从函数文件添加到perticular 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>