gpt4 book ai didi

javascript - 如何处理 WP 主题 .js 中文本的翻译

转载 作者:IT王子 更新时间:2023-10-28 23:53:30 26 4
gpt4 key购买 nike

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

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

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

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

赏金之后

I am putting a bounty since the questions given are generic whereas I am searching for a solution that can solve my issue.

我正在从事以前由某人构建的 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>

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

最佳答案

在 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);

关于javascript - 如何处理 WP 主题 .js 中文本的翻译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43589663/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com