Change language in YII

2020-04-17 07:10发布

After creating a new site with YII, I added a folder 'fr' in protected/messages and added a file 'site.php' which contains:

return array('hello' => 'bonjour');

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

标签: php yii
3条回答
劳资没心,怎么记你
2楼-- · 2020-04-17 07:17

You can set the default languages in the config/main.php as

return array(
    ...
    'sourceLanguage' => 'fr',
    'language'=>'en',
    ...
    'params' => array(
               ...
               'languages'=>array('en_us'=>'English', 'fr'=>'French', 'fa_ir'=>'فارسی'),
               ....
               ), 
); 

and change your language everywhere you like:

Yii::app()->language = Yii::app()->params->languages['fa_ir'];

also for more experience, maybe:

Yii::app()->language = Yii::app()->params->languages[$_GET['lang']];
查看更多
聊天终结者
3楼-- · 2020-04-17 07:30

You should set language in the controller if you want translations to work properly in all views.

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

查看更多
Explosion°爆炸
4楼-- · 2020-04-17 07:37

You forgot to set source language.

Into config:

return array(
   'sourceLanguage'=>'en',
),

Or app:

Yii::app()->sourceLanguage = 'en';
查看更多
登录 后发表回答