alexs/yii2-multilanguage

Multilanguage for Yii2 Framework.

Installs: 50

Dependents: 0

Suggesters: 0

Security: 0

Type:yii2-extension

1.1.11-stable 2019-04-16 19:22 UTC

README

Multilanguage extension for Yii2

1) Configure components

config/components.php

<?php
return [
    // ...
    'i18n' => [
        'translations' => [
            'app*' => [
                'class'=> 'yii\i18n\PhpMessageSource',
                'fileMap'=>[
                    'app'=>'app.php',
                ],
            ],
        ],
    ],
    'multilanguage'=>[
        'class'=>'alexs\yii2multilanguage\Multilanguage',
        'languages'=>[
            // the first language will be used by default
            //'id'=>['IETF' =>'Title']
            'ru'=>['ru-RU'=>'Русский'],
            'en'=>['en-US'=>'English'],
        ],
        'rules'=>[
            '<language:[a-z]{2}>'=>'index/index',
            '<language:[a-z]{2}>/<controller>'=>'<controller>',
            '<language:[a-z]{2}>/<controller>/<action>'=>'<controller>/<action>',
        ],
    ],
];

2) Create translations

messages/ru-RU/app.php

<?php
return [
    'Home page'=>'Главная страница',
    // ...
];

3) Create a view for the multilanguage widget

widgets/views/multilanguage-switcher.php

<?php
use yii\helpers\Url;

/** @var yii\web\View $this */
/** @var array $languages */
/** @var string $current */

if (!empty($languages)) { ?>
    <div class="languages">
        <ul>
        <?php foreach ($languages as $language_id=>$language) {
            list($language_ietf, $language_title) = each($language); ?>
            <?php if ($current === $language_ietf) { ?>
                <li><span><?=$language_title?></span></li>
            <?php } else { ?>
                <li><a href="<?=Url::to(['index/index', 'language'=>$language_id])?>"><?=$language_title?></a></li>
            <?php } ?>
        <?php } ?>
        </ul>
    </div>
<?php }

And use it:

<?php
use alexs\yii2multilanguage\MultilanguageSwitcher;
?>

<?=MultilanguageSwitcher::widget(['view'=>'@app/widgets/views/multilanguage-switcher'])?>

<?=Yii::t('app', 'Home page')?>
``