A
A
atis //2016-12-21 13:37:24
Yii
atis //, 2016-12-21 13:37:24

How to export localization for default language in Yii2 to files?

Straight to the point.

// app\config\web.php
return [
  // ...
  'sourceLanguage' => 'en-EN',
  'language' => 'en-EN',
  'i18n' => [
    'translations' => [
            'welcome' => [
                'class'   => 'yii\i18n\PhpMessageSource',
                'fileMap' => [
                    'welcome' => 'welcome.php'
                ],
            ],
        ],
  ]
  // ...
];

// app\messages\en-EN\welcome.php
return [
  'h1' => 'Hello!'
];

// app\messages\ru-RU\welcome.php
return [
  'h1' => 'Привет!'
];

<?php Yii::$app->language = 'en-EN' ?>

<!-- h1-->
<h1><?= Yii::t('welcome', 'h1') ?></h1>

<?php Yii::$app->language = 'ru-RU' ?>

<!-- Привет! -->
<h1><?= Yii::t('welcome', 'h1') ?></h1>

I expected to see Hello! instead of h1 .
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim Fedorov, 2016-12-21
@atis2345

In the built-in translation mechanism in Yii - if the application language matches the default language - no translation is performed. This behavior is set by default (which is why your code doesn't work) so that when the user gets to the default language version of the site, your application doesn't have to do the extra work of reading the translation files. You can disable this behavior by enabling forced translation, like so:

return [
  // ...
  'sourceLanguage' => 'en-EN',
  'language' => 'en-EN',
  'i18n' => [
    'translations' => [
            'welcome' => [
                'class'   => 'yii\i18n\PhpMessageSource',
                'forceTranslation' => true,
                'fileMap' => [
                    'welcome' => 'welcome.php'
                ],
            ],
        ],
  ]
  // ...
];

But in this case, you should understand that every time you access the site in the default language, Yii will shovel translation files....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question