在 YII 中更改语言 [英] Change language in YII
问题描述
使用 YII 创建新站点后,我在 protected/messages 中添加了一个文件夹fr",并添加了一个文件site.php",其中包含:
After creating a new site with YII, I added a folder 'fr' in protected/messages and added a file 'site.php' which contains:
返回数组('hello' => 'bonjour');
return array('hello' => 'bonjour');
在view/layout/main.php中,我添加了以下代码:
in the view/layout/main.php, I added following code:
<?php
// I change the language to english and french using session.
// This is just for example.
Yii::app()->language = 'fr';
// I also used Yii::app()->setLanguage('fr');
echo Yii::t('site','hello');
?>
但是语言没有翻译..我哪里错了.请推荐
But the language is not translated.. Where am I wrong. Please suggest
推荐答案
如果您希望翻译在所有视图中正常工作,您应该在控制器中设置语言.
You should set language in the controller if you want translations to work properly in all views.
为了将语言应用于所有控制器,在组件文件夹中创建新的 Controller.php
文件,其中包含扩展 CController
的 class Controller
,然后所有的控制器都应该扩展 Controller
类.在 Controller
类中覆盖 init()
方法(不要忘记调用 parent::init()
)并在那里设置语言.例如:
In order for language to be applied to all Controllers, create in components folder new Controller.php
file with class Controller
which extends CController
, and then all your controllers should extend Controller
class. in Controller
class override init()
method (don't forget to call parent::init()
) and set language there. For example:
class Controller extends CController
{
public $layout='//layouts/column1';
function init()
{
parent::init();
Yii::app()->language = 'fr';
}
}
通过这种方式,您可以在一个地方添加应应用于所有控制器的其他内容
This way you can add additional things which should apply to all Controllers at one place
这篇关于在 YII 中更改语言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!