我在WordPress中有自己的twig插件实现,我的翻译正在工作。你可以检查我的代码。
在测试代码时,请记住以下几点:
确保您的WordPress已设置locale
请确保您mo
文件是从最新版本的po
文件请确保mo
文件存在并由加载load_plugin_textdomain
函数您可以使用下面的脚本调试WordPress正在加载的翻译文件。
function wpse_287988_debug_mofiles( $mofile, $domain ) {
var_dump($mofile);
return $mofile;
}
add_filter( \'load_textdomain_mofile\', \'wpse_287988_debug_mofiles\', 10, 2);
function wpse_287988_terminate() {
die();
}
add_filter( \'wp_loaded\', \'wpse_287988_terminate\' );
工作细枝实施:
/**
* Load composer autloader
*/
require_once dirname(__FILE__) . \'/vendor/autoload.php\';
// Main class
class WPSE_287988_Twig {
/**
* Templates path
*/
private $templates_path;
/**
* Templates path
*/
private $options;
/**
* Twig instance
*/
private $twig;
/**
* Twig class constructor
*/
public function __construct() {
$this->templates_path = array();
$this->options = array();
$this->initialize_twig_options();
$this->initialize_twig();
$this->initialize_twig_functions();
$this->define_hooks();
}
/**
* Render method
*/
public function render( $template, $variables = array() ) {
return $this->twig->render( $template, $variables );
}
/**
* Initialize twig options
*/
private function initialize_twig_options() {
/**
* Resolve twig templates path
*/
$plugins_dir = plugin_dir_path( __FILE__ );
$this->templates_path[] = $plugins_dir;
$this->templates_path[] = $plugins_dir . \'templates\';
foreach ($this->templates_path as $path) {
if ( ! file_exists($path) ) {
mkdir($path);
}
}
/**
* Resolve twig env options, disable cache
*/
$this->options[\'cache\'] = false;
}
/**
* Initialize twig
*/
private function initialize_twig() {
$loader = new Twig_Loader_Filesystem( $this->templates_path );
$this->twig = new Twig_Environment($loader, $this->options );
}
/**
* Initialize additional twig funcitons
*/
public function initialize_twig_functions() {
/**
* Add gettext __ functions to twig functions.
*/
$function = new Twig_Function(\'__\', \'__\');
$this->twig->addFunction($function);
}
/**
* Load the plugin translations
*/
public function load_plugins_textdomain() {
$textdomain = \'wpse_287988\';
load_plugin_textdomain( $textdomain, false, basename( dirname( __FILE__ ) ) . \'/languages\' );
}
/**
* Define hooks required by twig class
*/
private function define_hooks() {
add_action( \'plugins_loaded\', array( $this, \'load_plugins_textdomain\' ) );
}
}
// End of main class
// Initialize class
function wpse_287988_twig() {
static $plugin;
if ( isset( $plugin ) && $plugin instanceof WPSE_287988_Twig ) {
return $plugin;
}
$plugin = new WPSE_287988_Twig();
return $plugin;
}
wpse_287988_twig();
// End of class initialization
// Testing code
function wpse_287988_test_render() {
$twig = wpse_287988_twig();
echo $twig->render(\'template.html.twig\');
die();
}
add_action(\'init\', \'wpse_287988_test_render\');
// End of testing code
我的
template.html.twig
文件:
{% set text = "Foo" %}
{{ __(text, \'wpse_287988\') }}
我将翻译保存在插件主目录的languages目录中。我的翻译文件是根据textdomain和区域设置命名的:
wpse_287988-pl_PL.po
和
wpse_287988-pl_PL.mo
.