yii2添加额外的语言

时间:2017-08-03 18:15:58

标签: php yii2 frameworks

我多次尝试为yii2基本模板添加额外的语言,我一直都失败了,让我告诉你我的所有代码,请你帮我解决我的错误,实际上网站没有说任何错误一切顺利,但语言没有转换到另一个

-----配置/ web.php ----

InputField

消息/ RU-RU / app.php

'id' => 'basic',
    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
    return [
    // set target language to be Russian
    'language' => 'ru-RU',

    // set source language to be English
    'sourceLanguage' => 'en-US',


];

    'i18n' => [
        'translations' => [
            'app*' => [
                'class' => 'yii\i18n\PhpMessageSource',
                //'basePath' => '@app/messages',
                //'sourceLanguage' => 'en-US',
                'fileMap' => [
                    'app' => 'app.php',
                    'app/error' => 'error.php',
                ],
            ],
        ],
    ],

        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'qwdqdq',
        ],

---------- siteController.php -------

<?php

return [
    'welcome' => 'Добро пожаловать',
    'log in' => 'Войти',
    'This is a string to translate!' => 'Это строка для перевода'
    //...
];

n $ this-&gt; goBack(); }

查看文件----- site / index.php

1 个答案:

答案 0 :(得分:0)

在你的config / web.php中添加'on beforeAction',如fallowing

return [
    'id' => 'basic',    
    // set target language to be Russian
    'language' => 'ru-RU',
    // set source language to be English
    'sourceLanguage' => 'en-US',

    'basePath' => dirname(__DIR__),
    'bootstrap' => ['log'],
    'components' => [
      ...
    ],
    'params' => [
       ...
    ],
    'on beforeAction' => function(){
        // get language from cookie, session or db 
        // and set it to app language
        Yii::$app->language = isset($_COOKIE['language'])?$_COOKIE['language']:Yii::$app->language;
    }
];

在SiteControler函数actionChangeLang中替换行

 \Yii::$app->language = $local;

setcookie("language", $local);

现在,您将能够更改区域设置并将其保留在请求之间。 在我的示例中,我使用了cookie,但您也可以使用任何类型的存储来存储您的语言环境。