yii:国际化(i18n)和动态网址管理器

时间:2012-08-07 13:49:00

标签: routes yii url-routing

我想知道在Yii框架中实现“国际化(i18n)”和“动态URL管理”的更好方法。

(难以维护)临时解决方案:

// protected/config/main.php
'language' => 'es',
...
'urlManager'=>array(
        'urlFormat'=>'path',
        'showScriptName' => false,
        'rules'=>array(
            // pages
            'es/turismo/<slug:>' => array('visit/page', 'defaultParams' => array('lang' => 'es'), 'urlSuffix' => '.html'),
            'it/visita/<slug:>' => array('visit/page', 'defaultParams' => array('lang' => 'it'), 'urlSuffix' => '.html'),
            'en/travel/<slug:>' => array('visit/page', 'defaultParams' => array('lang' => 'en'), 'urlSuffix' => '.html'),
            'turismo/<slug:>' => array('visit/page', 'urlSuffix' => '.html'),

            // home
            'es/turismo' => array('visit/index', 'defaultParams' => array('lang' => 'es'), 'urlSuffix' => '.html'),
            'it/visita' => array('visit/index', 'defaultParams' => array('lang' => 'it'), 'urlSuffix' => '.html'),
            'en/travel' => array('visit/index', 'defaultParams' => array('lang' => 'en'), 'urlSuffix' => '.html'),

            // contact us
            'es/contactenos' => array('site/contact', 'defaultParams' => array('lang' => 'es'), 'urlSuffix' => '.html'),
            'it/contattaci' => array('site/contact', 'defaultParams' => array('lang' => 'it'), 'urlSuffix' => '.html'),
            'en/contact-us' => array('site/contact', 'defaultParams' => array('lang' => 'en'), 'urlSuffix' => '.html'),

        ),
    ),
...


// protected/controllers/VisitController.php
...
public function actionIndex($lang = 'es'){
    Yii::app()->language = $lang;
    ...
}
public function actionPage($slug, $lang = 'es'){
    Yii::app()->language = $lang;
    ...
}
...

这意味着,每个控制器的新配置'urlManager'规则,并始终为每个控制器操作传递$ lang参数。一个现实的例子:

montmartrebutte.com

我尝试了其他一些选项却没有成功:

Yii Framework Forum: Dynamic URL manager routes

谢谢!

1 个答案:

答案 0 :(得分:3)

规则:

'<lang:(es|it|en)>/(turismo|visita|travel)/<slug:>' => array('visit/page', 'urlSuffix' => '.html'),

控制器:

class VisitController extends Controller
{
    public function actionPage($slug)
    {

    }
}

父控制器(如果您不使用模块):

class Controller extends CController
{
    public function beforeAction($action)
    {
        Yii::app()->language = Yii::app()->request->getQuery('lang', 'es');
        return parent::beforeAction($action);
    }
}