Revision #4 has been created by rackycz on Jan 21, 2021, 2:29:11 PM with the memo:
Translations
« previous (#3) next (#5) »
Changes
Title
unchanged
Yii v2 snippet guide III
Category
unchanged
Tutorials
Yii version
unchanged
2.0
Tags
unchanged
Content
changed
# Switching languages and Language in URL
I already [wrote](https://www.yiiframework.com/wiki/2552/yii-v2-snippet-guide#i18n-translations) how translations work. Here I will show how language can be switched and saved into the URL.
So let's add the language switcher into the main menu:
```php
echo Nav::widget([
'options' => ['class' => 'navbar-nav navbar-right'],
'items' => [
['label' => 'Language', 'encode'=>false, 'items' => [
['label' => 'German' , 'url' => \yii\helpers\Url::current(['sys_lang' => 'de']) ],
['label' => 'English', 'url' => \yii\helpers\Url::current(['sys_lang' => 'en']) ],
],
]
```
Now we need to process the new GET parameter and save it to Session in order to keep the new language. Best is to create a BaseController which will be extended by all controllers. Its content looks like this:
```php
<?php
namespace app\controllers;
use yii\web\Controller;
class _BaseController extends Controller {
public function beforeAction($action) {
if (isset($_GET['sys_lang'])) {
switch ($_GET['sys_lang']) {
case 'de':
$_SESSION['sys_lang'] = 'de-DE';
break;
case 'en':
$_SESSION['sys_lang'] = 'en-US';
break;
}
}
if (!isset($_SESSION['sys_lang'])) {
$_SESSION['sys_lang'] = \Yii::$app->sourceLanguage;
}
\Yii::$app->language = $_SESSION['sys_lang'];
return true;
}
}
```