4
votes

I would like to know a better way to implement "internationalization (i18n)" and "dynamic URL management" in Yii framework.

A (difficult to maintain) temporary solution:

// 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;
    ...
}
...

This implies, new config 'urlManager' rules for each controller and always pass the $lang parameter for each controller action. A live example:

montmartrebutte.com

I tried some other options without success:

Yii Framework Forum: Dynamic URL manager routes

Thanks!

1

1 Answers

3
votes

Rule:

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

Controller:

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

    }
}

Parent controller (if you don't use modules):

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