Извличане на преводи от всички twig шаблони (CodeIgniter)

Ние използваме Twig шаблонен двигател за нашия базиран на CodeIgniter проект. И се сблъскахме с проблем с преводими извличания на низове от twig шаблон.

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

xgettext не може да извлича преводими низове от такива шаблони, но може да анализира компилирани (в php) twig шаблони и да извлича преводими низове от там. Така че проблемът може да бъде решен чрез компилиране на всички шаблони в php и след това чрез извличане на низове от него.

И тук е въпросът:

Как да принудя Twig да компилира набор от разширения от командния ред?


person Sergey P. aka azure    schedule 08.11.2013    source източник


Отговори (1)


Резултатът от моите разследвания завърши със следния php скрипт. Предназначен е да се използва, както следва:

./compile_twig_templates.php /path/to/tmp/dir

Скриптът ще запълни tmp dir с компилирани шаблони (чисти .php файлове), които могат да бъдат анализирани от 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);
        }
    }
}

?>
person Sergey P. aka azure    schedule 02.12.2013