Yii urlManager language in URL

杀马特。学长 韩版系。学妹 提交于 2019-12-06 04:34:33

问题


I am trying to add a language to the url with following syntax: http://www.example.com/en/site/page/view/about

What I have so far works with short urls like: http://www.example.com/en/site/contact but not with long once as in my first example

Here is what I have so far:

/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:


I had same problem, and following rules work for me also with submodules and any number of params:

                 '<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 is special value for module, _c for controller and _a for action.



来源:https://stackoverflow.com/questions/2574181/yii-urlmanager-language-in-url

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!