URL中的Yii urlManager语言

时间:2010-04-04 10:45:48

标签: php url-routing yii

我正在尝试使用以下语法向网址添加语言:     http://www.example.com/en/site/page/view/about

到目前为止我所使用的短网址如下:     http://www.example.com/en/site/contact 但不是像我的第一个例子那样长一次

这是我到目前为止所做的:

/config/main.php

'urlManager'=>array(
    'class'=>'application.components.MyCUrlManager',
    'urlFormat'=>'path', 'showScriptName'=>false,
    'rules'=>array(
        '<language:\w+>/<controller:\w+>/<id:\d+>'=>'<controller>/view',
        '<language:\w+>/<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
        '<language:\w+>/<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
    ),
),

<?php // components/MyCUrlManager.php

class MyCUrlManager extends CUrlManager
{
    public function createUrl($route,$params=array(),$ampersand='&')
    {
        if(isset($_POST['_lang']))
        {
            Yii::app()->setLanguage($_POST['_lang']);
            $route['language']=Yii::app()->language;
        }
        elseif (!isset($route['language']))
        {
            $route['language']=Yii::app()->language;
        }
        else
        {
            Yii::app()->setLanguage($route['language']);
        }
        return parent::createUrl($route, $params, $ampersand);
    }
}
?>

class LangBox extends CWidget {

    public function run() {

        $currentLang = Yii::app()->language;
        require_once 'Zend/Locale.php';
        $locale = new Zend_Locale();
        //$siteLanguages = $this->getLang();
        $siteLanguages = array('en','de','tr');
        foreach($siteLanguages as $value){
                $list[$value] = $locale->getTranslation($value, 'Language', $value);
        }
        asort($list);
        $this->render('langBox', array('currentLang' => $currentLang, 'list'=>$list));
    }
}

1 个答案:

答案 0 :(得分:5)

我有同样的问题,以下规则也适用于子模块和任意数量的参数:

                 '<lang:[a-z]{2}>/<_m>/<_c>' => '<_m>/<_c>',
                 '<lang:[a-z]{2}>/<_m>/<_c>/<_a>*' => '<_m>/<_c>/<_a>',
                 '<lang:[a-z]{2}>/<_m>/<_a>' => '<_m>/<_a>',
                 '<lang:[a-z]{2}>/<_c>' => '<_c>',
                 '<lang:[a-z]{2}>/<_c>/<_a>' => '<_c>/<_a>',

_m是模块的特殊值,_c表示控制器,_a表示操作。