Search code examples
internationalizationyii2yii2-basic-app

Yii2 translation does not work in config/params


I have the following config/params.php in my :

<?php
$siteName = Yii::t('app','Site Name'); //previously, this value had been placed directly in the array just a try to make it available to the translation
return [
    'adminEmail' => '[email protected]',
    'siteName' => $siteName,
    'textToPrint' => null,
    'meta-description' => $siteName,
];

The message Site Name is already has a translation in @app/messages/ar/app.php and the translation is working fine on the website.

However, when I try to use meta tag description in the main layout like the following:

<meta name="description" content="<?= Yii::$app->params['meta-description'] ?>" />

So, in any view, if I have set a value to Yii::$app->params['meta-description'] it should be printed out in the layout while when there is no any supplied value to it, it should print the initial value defined in config/params.php.

The problem is, the initial value is printed without translation. This is issue may be solved by translating the string in the main layout as the following:

<meta name="description" content="<?= Yii::t('app',Yii::$app->params['meta-description']) ?>" />

Due to the above solution I have two questions:

  1. Why the string did not be translated in the config/params.php?
  2. Does the heavy use of Yii::t() with many untranslated strings, (in my case, when I decide to override the value Yii::$app->params['meta-description'] in a view), has any performance issue?

Solution

  • Answers:

    1. Because config/params.php file will merge with main config before initialization of main application. For translation will used \yii\i18n\I18N component.

    2. Yii2::t() is not heavy method. But if you have any problems with performance, you can override this method and execute Yii:$app->getI18n()->translate() only for existing strings, or enable cache this values.