Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Translations in sourceLanguage does not work in Yii2 application

I'm using a translations based on keywords in my Yii2 application (I know, that this isn't best option, but I don't have other). I've prepared @app/messages/pl/app.php and @app/messages/en/app.php files with translation strings using keywords, instead of full-featured sentences or words:

<?php
    return [
        'name_english'=>'Name in English',
        'keywords_english'=>'Keywords in English'
    ];
?>

I have set my application to use Polish language as default:

'language' => 'pl',
'sourceLanguage' => 'en',

And I'm invoking translation:

Yii::t('app', 'keywords_english');

Everything works fine, when language is actually set to base, Polish (pl):

enter image description here

But, when I change it to English (en; either by setting Yii::$app->language during runtime or by changing application configuration), translation is not performed and I'm getting keywords_english:

enter image description here

I have put die() in the beginning of @app/messages/pl/app.php and @app/messages/en/app.php files and I can clearly see, that when language is set to English, second file is not being included by Yii2 (application run follows), while, when language is Polish, first file is included and application flow breaks on that die().

What am I missing? Why Yii2 is not using translations from @app/messages/en/app.php file, if language is set to English (en)?

EDIT: By default, I was not altering default i18n component configuration in my application's configuration as I found no need for that. Translation files are stored in default position (@app/messages/<language>/) and are using default class (yii\i18n\PhpMessageSource). And this is working for all languages except sourceLanguage. At some point, I tried to alter configuration:

'i18n' => [
    'translations' => [
        '*' => [
            'class' => 'yii\i18n\PhpMessageSource',
            'sourceLanguage' => 'en',
            'basePath' => '@app/messages'
        ],
    ],
],

But, it brought no change (why should it -- it still uses default settings).

like image 211
trejder Avatar asked Apr 07 '15 09:04

trejder


1 Answers

According to samdark at Yii Forum, this is by design. Translations are not performed, if language = sourceLangage.

To workaround this, and force translations in this case, one must set forceTranslation to true.

Therefore, one must add / modify i18n component in components section of application's config in the way similar to this:

'i18n' => [
    'translations' => [
        'app' => [
            'class' => 'yii\i18n\PhpMessageSource',
            'forceTranslation' => true
        ],
    ],
],
like image 86
trejder Avatar answered Oct 12 '22 23:10

trejder