我们正在为基于 CodeIgniter 的项目使用 Twig 模板引擎。我们遇到了从树枝模板中提取可翻译字符串的问题。
{% trans %}Text to translate{% endtrans %}
xgettext 无法从此类模板中提取可翻译字符串,但它可以解析已编译(到 php)的树枝模板并从那里提取可翻译字符串。因此,可以通过将所有模板编译为 php,然后从中提取字符串来解决问题。
这是一个问题:
如何强制 Twig 从命令行编译扩展集?
我们正在为基于 CodeIgniter 的项目使用 Twig 模板引擎。我们遇到了从树枝模板中提取可翻译字符串的问题。
{% trans %}Text to translate{% endtrans %}
xgettext 无法从此类模板中提取可翻译字符串,但它可以解析已编译(到 php)的树枝模板并从那里提取可翻译字符串。因此,可以通过将所有模板编译为 php,然后从中提取字符串来解决问题。
这是一个问题:
如何强制 Twig 从命令行编译扩展集?
我的调查结果以以下 php 脚本结束。它的用途如下:
./compile_twig_templates.php /path/to/tmp/dir
脚本将使用已编译的模板(纯 .php 文件)填充 tmp 目录,这些模板可以像往常一样由 xgettext 解析
#!/usr/bin/php
<?php
if (!$argv) {
echo 'Script should be runned from command line';
exit(1);
}
if ( !$argv[1] ) {
echo "Usage: ".$argv[0]." path_to_cache_dir\n";
echo "Example: ".$argv[0]." /tmp/twig_cache\n";
exit(1);
}
if ( !is_dir($argv[1])) {
echo "$argv[1] is not a directory";
exit(1);
}
$script_path = dirname($argv[0]);
require_once 'libraries/Twig/lib/Twig/Autoloader.php';
Twig_Autoloader::register();
require_once (string) "libraries/Twig-extensions/lib/Twig/Extensions/Autoloader.php";
Twig_Extensions_Autoloader::register();
//path to directory with twig templates
$tplDir = $script_path.'/views';
$tmpDir = $argv[1];
$loader = new Twig_Loader_Filesystem($tplDir);
// force auto-reload to always have the latest version of the template
$twig = new Twig_Environment($loader, array(
'cache' => $tmpDir,
'auto_reload' => true
));
//add all used extensions
$twig->addExtension(new Twig_Extensions_Extension_I18n());
//add all used custom functions (if required)
$twig->addFunction('base_url', new Twig_Function_Function('base_url'));
// Adding PHP helper functions as filters:
$twig->addFilter(new Twig_SimpleFilter('ceil', 'ceil'));
echo "Iterating over templates!\n";
// iterate over all your templates
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tplDir), RecursiveIteratorIterator::LEAVES_ONLY) as $file)
{
echo "Compiling ".$file."\n";
// force compilation
if ($file->isFile()) {
try {
$twig->loadTemplate(str_replace($tplDir.'/', '', $file));
} catch (Twig_Error_Syntax $e) {
echo "Caught exeption! $e\n";
var_dump($e);
exit(2);
}
}
}
?>