Introduction
We can easily have a multilingual site if we put a "lang" parameter that comes via GET. For example:
echo CHtml::link('Games', array('/site/games', 'lang' => 'en')); echo CHtml::link('Juegos', array('/site/games', 'lang' => 'es')); echo CHtml::link('Contact', array('/site/contact', 'lang' => 'en')); echo CHtml::link('Contacto', array('/site/contact', 'lang' => 'es'));
Then, in Controller.php, we need to put this piece of code:
public function beforeAction($action) { if(isset($_GET['lang'])) { Yii::app()->setLanguage($_GET['lang']); } else { Yii::app()->setLanguage('en'); } return true; }
Finally we can add the following rules:
'urlManager'=>array( 'urlFormat'=>'path', 'showScriptName'=>false, 'rules'=>array( '<lang:\w+>'=>'site/index', '<lang:\w+>/<action>' => 'site/<action>', ) ),
The problem
This leads to URLs like these:
- http://myweb.com/en/games (English)
- http://myweb.com/es/games (Spanish)
- http://myweb.com/en/contact (English)
- http://myweb.com/es/contact (Spanish)
This is fine to have a multilingual site. But, we can go one step further. What if we want URLs like these:
- http://myweb.com/en/games (English)
- http://myweb.com/es/juegos (Spanish)
- http://myweb.com/en/contact (English)
- http://myweb.com/es/contacto (Spanish)
That is, every URL has its particular path. It changes the whole URL, not just the two initial letters (en/es).
The solution
'urlManager'=>array( 'matchValue'=>true, 'urlFormat'=>'path', 'showScriptName'=>false, 'rules'=>array( '<lang:\w+>'=>'site/index', '<lang:es>/juegos'=> 'site/games', '<lang:en>/games'=> 'site/games', '<lang:es>/contacto'=> 'site/contact', '<lang:en>/contact'=> 'site/contact', '<lang:\w+>/<action>' => 'site/<action>', ) ),
Take note that we also added 'matchValue' => true to the urlManager array.