I have Yii2 advanced template, I want to set translation for my frontend views, here is what I did:
frontend/config/main.php:
'sourceLanguage'=>'en-US',
'language'=>'en-US',
'components' => [
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
'basePath' => '@common/messages',
'sourceLanguage' => 'en-US',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
],
]
then I added i18n.php
in common/config:
<?php
return [
'sourcePath' => __DIR__. '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR,
'languages' => ['fr-FR','en-US'], //Add languages to the array for the language files to be generated.
'translator' => 'Yii::t',
'sort' => false,
'removeUnused' => false,
'only' => ['*.php'],
'except' => [
'.svn',
'.git',
'.gitignore',
'.gitkeep',
'.hgignore',
'.hgkeep',
'/messages',
'/vendor',
],
'format' => 'php',
'messagePath' => __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'messages',
'overwrite' => true,
];
and the common/messages/en-US/app.php:
<?php
return[
// Menu texts
'menu.login'=>'login',
];
and I used it in the views as : Yii::t('app', 'menu.login');
but the translation didn't work, it displayed as menu.login
You Just Follow This Steps......
Step 1: In the
common
directory , createmessages
folder.Step 2: Create
i18n.php
file insidecommon/config
directory with following content:Note: Make sure to add all required languages to 'languages' array. In the above example I have added English and Russian for Generate Yii2 Framework multi language.
Step 3: Add the
i18n
component inconfig
filecommon/main.php
configuration as follows:Step 4:
Add the language module in common config file to use the default language on your app, such as:
'language' => 'en-EN'
insidecommon/main.php
.You now can use
Yii::$app->language = ‘en-EN’
at any runtime like URL request, query code.Note: In any Model, Controller Generate by Gii, you can see Enable I18n ticket choice, just enable this for Multi language. Gii Tool will auto generate a Model has pre-defined as below, due to
frontent
orbackend
folder:Step 5: Run this command line from Yii2 app folder:
This command line will Generate Yii2 Framework multi language translation files inside
common/messages
and divide intofrontend
andbackend
folder.If you want to edit the translate text, just open
backend.php
orfrontend.php
file and edit.