yii2 basic multiple language

我是研究僧i 提交于 2019-12-08 07:06:57

问题


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. 


回答1:


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();
}


来源:https://stackoverflow.com/questions/45453805/yii2-basic-multiple-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!