Reputation: 175
I need to make website with 2 languages in Yii2 basic framework, however, I researched tons of times on google and other search engines and I could only find yii2 advanced internalisation. I need for basic mode, please if you have source codes for yii2 basic multiple languages or if you know any link or video tutorial about yii2 basic internalisation, please kindly share with me, I would be greatly appriciated.
I am looking forward from hearing from you soon.
Upvotes: 1
Views: 5970
Reputation: 271
The best tutorial is official documentation. So, look here
In basic app, i18n implementation has not difference from advanced app.
At first, set up your main config adding following keys:
return [
// set target language to be Russian
'language' => 'ru-RU',
// set source language to be English
'sourceLanguage' => 'en-US',
......
];
After that, create new file /messages/ru-RU/app.php
(for implementing translation for ru-RU
language. If you target language will be es-MX
, so, that will be /messages/es-MX/app.php
Now In this file, you can implement translation of your strings
<?php
/**
* Translation map for ru-RU
*/
return [
'welcome' => 'Добро пожаловать',
'log in' => 'Войти',
'This is a string to translate!' => 'Это строка для перевода'
//...
];
When your file is ready, just configure i18n component in your main config file like this:
'components' => [
// ...
'i18n' => [
'translations' => [
'app*' => [
'class' => 'yii\i18n\PhpMessageSource',
//'basePath' => '@app/messages',
//'sourceLanguage' => 'en-US',
'fileMap' => [
'app' => 'app.php',
'app/error' => 'error.php',
],
],
],
],
],
Finaly, you can show your strings using echo \Yii::t('app', 'This is a string to translate!');
So, you'll see This is a string to translate!
when your app in en-US
language, and Это строка для перевода
when app in ru-RU
;
To change target language, just create a simple action, something like
public function actionChangeLang($local)
{
$available_locales = [
'ru-RU',
'en-US'
];
if (!in_array($local, $available_locales)) {
throw new \yii\web\BadRequestHttpException();
}
\Yii::$app->language = $local;
return $this->goBack();
}
Upvotes: 6