Back to Home

Multilanguage widget in YII2 without using a database

yii2 · yii2 multi language

Multilanguage widget in YII2 without using a database

  • Tutorial
An example of internationalizing a site on Yii2 in two languages: ru and en. The component responsible for internationalization is already built in Yii2, it is called i18n. In order to start using it, just add it to the application configuration in the components section.

I use the advanced template so file locations may vary.

goal

  1. switching a site between two languages: ru and en;
  2. displaying the language in the address bar in the form site.com/en/;
  3. automatic redirection of the user to the language most suitable for him if he switched to the site without indicating the language;
  4. translations should be stored in PHP files in the form of arrays;

Configuration

Edit the configuration file, in my case it is \ frontend \ config \ main.php

return [
    'language'=>'en',
// язык по умолчанию, на который будет перенаправлен пользователь в случае невозможности определения для него наиболее подходящего языка на основе данных предоставляемых его браузером.
    'components' => [
        'urlManager' => [
            'enablePrettyUrl' => true,
            'showScriptName' => false,
            'class' => 'frontend\widgets\MultiLang\components\UrlManager',
// заменяем стандартный урл.менеджер на наш.
            'languages' => ['ru', 'en'],
//список языков на который переводим сайт
            'enableDefaultLanguageUrlCode' => true,    
// показываем идентификатор языка по умолчанию, если false, то при в корне сайта не будет виден идентификатор языка  www.site.com/   , с true – www.site.com/ru
            'rules'=>[
                '/' => 'site/index',
                '//'=>'/',
            ],
        ],
        'i18n' => [
            'translations' => [
                'app*' => [
// app название нашего php файла переводов который нужно создать app.php (может быть любым)
                    'class' => 'yii\i18n\PhpMessageSource',
                    'basePath' => '@frontend/messages',
// путь для нашего файла переводов frontend/messages/ru/app.php
                    'sourceLanguage' => 'en',
// язык с какого переводим, то есть, в проекте все надписи пишем на английском
                ],
            ],
        ],
    ],

'class' => 'frontend \ widgets \ MultiLang \ components \ UrlManager', the contents of the file are taken from here , you can follow the instructions of the developer and use composer, but we do the widget, so just copy UrlManager.php to our widget.

The file with the list of translations frontend / messages / ru / app.php, must contain an array

return [
    ...
    'Example text...' => 'Пример текста...',
    ...
];

We use the built-in method t


In the first argument, specify the category, we have one - app, you can create many translation files. In the second argument, we write the English text as it should be displayed on the site.

Switching languages.

Create a MultiLang folder in the widget folder, it looks like this for me:

Frontend\
    Widgets\
       MultiLang\
	  Components\
	    UrlManager.php
	  Views\
	    View.php
	  MultiLang.php

To show the language switch anywhere, call

'pull-right language']); ?>

Do not forget to write the path to the widget

use frontend\widgets\MultiLang\MultiLang;


The contents of the class frontend \ widgets \ MultiLang \ MultiLang.php

render('view', [
            'cssClass' => $this->cssClass,
        ]);
    }
}

Content view frontend \ widgets \ MultiLang \ views \ view.php

language; ?>

Conclusion

In general, the implementation of internationalization in Yii2 is not difficult, it turned out to be a simple widget with three files.

UrlManager.php taken from here . MultiLang.php just renders the view. View.php the view itself.

Read Next