【发布时间】:2017-08-03 18:15:57
【问题描述】:
我多次尝试为 yii2 基本模板添加额外的语言,但我都失败了,让我向你展示我所有的代码,你能帮我解决我的错误吗,实际上网站并没有说任何错误,一切正常,但语言没有切换到另一种语言
-----config/web.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',
],
消息/ru-RU/app.php
<?php
return [
'welcome' => 'Добро пожаловать',
'log in' => 'Войти',
'This is a string to translate!' => 'Это строка для перевода'
//...
];
---------siteController.php------
Class SiteController extends Controller
{
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;
retur
n $this->goBack(); }
查看文件-----site/index.php
【问题讨论】:
-
这是因为您只为当前实例设置了语言。当您返回 $this->goBack() 时,会进行重定向并使用配置中设置的默认语言创建 Yii::$app 的新实例
-
更好的方法是设置一个cookie并在发出任何请求之前检查它并设置语言
标签: php yii2 frameworks