It would be convenient to just be able to use a templating filter multilingualism
{# tr filter #} {{ Hello|translate }}
|
Nov '13 |
4 |
750 |
1 |
It would be convenient to just be able to use a templating filter multilingualism
{# tr filter #} {{ Hello|translate }}
If you have a service for multi-lingualism, you can use:
$compiler = $volt->getCompiler();
$compiler->addFilter('translate', function($resolvedArgs) {
return '$this->trans->query(' . $resolvedArgs . ')';
});
If you pass a variable ($t) to your views, you can use:
$compiler = $volt->getCompiler();
$compiler->addFilter('translate', function($resolvedArgs) {
return '$t->query(' . $resolvedArgs . ')';
});
If you have a static method, you can use:
$compiler = $volt->getCompiler();
$compiler->addFilter('translate', function($resolvedArgs) {
return 'My\Translate::query(' . $resolvedArgs . ')';
});
If you have a PHP function, you can use:
$compiler = $volt->getCompiler();
$compiler->addFilter('translate', function($resolvedArgs) {
return 'my_translate(' . $resolvedArgs . ')';
});
Almost perfect, but the placeholders passed to my filter are not being replaced by the values.
Here is how I assigned translator to volt as a filter:
// Translator
$di->set('translator', function() use ($app, $config) {
$language = $app->request->getBestLanguage();
$baseCatalogPathTemplate = APP_ROOT . "resources/translations/messages.%s.php";
$languageCatalogPath = sprintf($baseCatalogPathTemplate, $language);
$fallbackCatalogPath = sprintf($baseCatalogPathTemplate, $config->locale);
$messagesCatalog = file_exists($languageCatalogPath) ? require $languageCatalogPath : require $fallbackCatalogPath;
return new NativeArray(["content" => $messagesCatalog]);
});
// Template Engine
$di->set('view', function() {
$view = new View();
$view
->setViewsDir(__DIR__ . '/../resources/views/')
->registerEngines(array(
'.volt' => function($view, $di) {
$options = [
'compileAlways' => (APP_ENV != APP_ENV_PROD),
'compiledPath' => APP_ROOT . '/cache/views/'
];
$volt = new Volt($view, $di);
$volt->setOptions($options);
$volt->getCompiler()->addFilter('trans', function($resolvedArgs) {
return '$this->translator->query(' . $resolvedArgs . ')';
});
return $volt;
}
))
;
return $view;
});
Here is a snippet from a volt template that is being translated, but the placeholders were not replaced with variables, as they should be:
{{ 'Foo has value %foo%'|trans(['%foo%': 'bar']) }}