How to have truly multilingual URLs

You are viewing revision #26 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version.

next (#27) »

  1. Introduction
  2. The problem
  3. The solution

Introduction

We can easily have a multilingual site if we put a "lang" parameter that comes via GET. For example:

<?php 
echo CHtml::link('Games', array('/site/games', 'lang' => 'en')); 
echo CHtml::link('Juegos', array('/site/games', 'lang' => 'es')); 
echo CHtml::link('Services', array('/site/services', 'lang' => 'en')); 
echo CHtml::link('Servicios', array('/site/services', '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:

This is fine to have a multilingual site. But, we can go one step further. What if we want URLs like these:

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>/servicios'=> 'site/services',
           '<lang:en>/services'=> 'site/services',
	       '<lang:\w+>/<action>' => 'site/<action>',
     )
),

(Take note that we also added 'matchValue' => true to the urlManager array.)

0 0
3 followers
Viewed: 18 020 times
Version: Unknown (update)
Category: How-tos
Written by: oligalma
Last updated by: oligalma
Created on: Sep 29, 2015
Last updated: 3 years ago
Update Article

Revisions

View all history

Related Articles