Answer the question
In order to leave comments, you need to log in
How to attach Gettext to Twig templates in YII2?
Hello,
Can you tell me how to attach localization via Gettext to Twig templates in Yii2?
Installed via composer yiisoft/yii2-app-basic, added yiisoft/yii2-twig. Added to config:
'view' => [
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'extensions' => [
'Twig_Extensions_Extension_I18n'
],
],
],
],
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\GettextMessageSource',
'basePath' => '@app/messages',
'sourceLanguage' => 'en-US',
],
],
],
$app->register(new Silex\Provider\TranslationServiceProvider(), array(
'locale_fallbacks' => array('ru'),
));
$app['translator'] = $app->share($app->extend('translator', function($translator, $app) {
$translator->addLoader('po', new PoFileLoader());
$translator->addResource('po', __DIR__.'/../po/messages.en.po', 'en');
return $translator;
}));
$app['twig']->addExtension(new Symfony\Bridge\Twig\Extension\TranslationExtension($app['translator']));
$app->before(function () use ($app) {
$app['locale'] = 'ru';
});
Answer the question
In order to leave comments, you need to log in
By analogy with Silex, it proxyed a translation request to the system \Yii::t, which can correctly load files with translations. The result is an extension
namespace app\components;
use Twig_Extension;
use Twig_Extensions_TokenParser_Trans;
use Twig_SimpleFilter;
class Twig_I18n_Extension extends Twig_Extension {
/**
* Translation message context
* @var string
*/
public $category = 'app';
/**
* Returns the token parser instances to add to the existing list.
*
* @return array An array of Twig_TokenParserInterface or Twig_TokenParserBrokerInterface instances
*/
public function getTokenParsers()
{
return array(new Twig_Extensions_TokenParser_Trans());
}
/**
* {@inheritdoc}
*/
public function getFilters()
{
return array(
new \Twig_SimpleFilter('trans', array($this, 'trans')),
);
}
/**
* @param string $category the message category.
* @param string $message the message to be translated.
* @param array $arguments
* @param string $language the language code (e.g. `en-US`, `en`). If this is null, the current
* will be used.
* @return string
*/
public function trans($message, array $arguments = [], $category = null, $language = null)
{
if (!$category) {
$category = $this->category;
}
return \Yii::t($category, $message, $arguments, $language);
}
/**
* Returns the name of the extension.
*
* @return string The extension name
*/
public function getName()
{
return 'i18n';
}
}
'view' => [
'renderers' => [
'twig' => [
'class' => 'yii\twig\ViewRenderer',
'extensions' => [
'app\components\Twig_I18n_Extension'
],
],
],
],
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question