从所有树枝模板中提取翻译(CodeIgniter)

时间:2013-11-08 16:04:59

标签: php codeigniter templates twig gettext

我们正在为基于CodeIgniter的项目使用Twig模板引擎。我们遇到了来自twig模板的可翻译字符串提取的问题。

{% trans %}Text to translate{% endtrans %}

xgettext无法从这些模板中提取可翻译的字符串,但它可以解析编译的(到php)树枝模板并从那里提取可翻译的字符串。 所以问题可以通过将所有模板编译成php然后从中提取字符串来解决。

以下是问题:

如何强制Twig从命令行编译扩展集?

1 个答案:

答案 0 :(得分:0)

我的调查结果以下面的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);
        }
    }
}

?>