M
M
matperez2014-09-29 16:46:25
Yii
matperez, 2014-09-29 16:46:25

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'
            ],
          ],
        ],
      ],

The template engine works, you can render via $this->render('someaction.twig');
I also corrected the MessageSource in the config so that Yii::t uses PO files to store translations.
'i18n' => [
        'translations' => [
          'app*' => [
            'class' => 'yii\i18n\GettextMessageSource',
            'basePath' => '@app/messages',
            'sourceLanguage' => 'en-US',
          ],
        ],
      ],

Now how to tie Gettext specifically to Twig, so that you can use {{'some text'| trans}} in templates? I read the doc on Twig twig.sensiolabs.org/doc/extensions/i18n.html, but could not implement it.
In silex it was somehow like this:
$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';
});

//upd
Added "twig/extensions": "~1.1" dependencies and corrected the config for loading the Twig_Extensions_Extension_I18n extension. {{'translate me' | trans}} outputs a void now, but the function is known.
Another question is how to make it load translations from a given *.po file?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
matperez, 2014-09-29
@matperez

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';
  }
}

The render settings are like this:
'view' => [
        'renderers' => [
          'twig' => [
            'class' => 'yii\twig\ViewRenderer',
            'extensions' => [
              'app\components\Twig_I18n_Extension'
            ],
          ],
        ],
      ],

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question