Welcome Guest, Not a member yet? Register   Sign In
Is possible change the uri (name of controller) in the URL?
#1

[eluser]jesusruiz[/eluser]
Hello and thanks for reading this message.

I hope that you understand what I need to do.

I am doing a multilingual website, using CodeIgniter 2.1 internationalization i18n:
http://codeigniter.com/wiki/CodeIgniter_...ation_i18n

I have two controllers very simple:

DEFAULT CONTROLLER: INDEX

Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Index extends CI_Controller {
    
         public function __construct() {
            parent::__construct();
        }


        public function index()
        {
            $this->lang->load('about');
            if ($this->lang->lang() == "es")
            {
            $data['title'] = 'Bienvenido a la web';
            $data['main_content'] = '/es/index';
            $this->load->view('template/template',$data);
            }
            else
            {
            $data['title'] = 'Welcome to the Website';
            $data['main_content'] = '/en/index';
            $this->load->view('template/template',$data);  
            }
        }
}

and CONTROLLER: ABOUT

Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class About extends CI_Controller {
    
         public function __construct() {
            parent::__construct();
        }


        public function index()
        {
            $this->lang->load('about');
            if ($this->lang->lang() == "es")
            {
            $data['title'] = 'Acerca de Nosotros';
            $data['main_content'] = '/es/about';
            $this->load->view('template/template',$data);
            }
            else
            {
            $data['title'] = 'About us';
            $data['main_content'] = '/en/about';
            $this->load->view('template/template',$data);  
            }
        }
}


I need to make the url for each language could be different, for example:
en/about_us
es/acerca_de

But the problem is that in the url, by default shows the name of the contoller:
en/about
es/about

My code in Routes.php file is:
Code:
$route['default_controller'] = "index";
$route['404_override'] = '';

// example: '/en/about' -> use controller 'about'
$route['^en/(.+)$'] = "$1";
$route['^es/(.+)$'] = "$1";

// '/en' and '/es' -> use default controller
$route['^en$'] = $route['default_controller'];
$route['^es$'] = $route['default_controller'];

Any suggestions or help?.

Thousands of thanks and greetings.
#2

[eluser]toopay[/eluser]
You can use :
Code:
$route['(en|es)/(about_us|acerca_de)'] = "about/$1";
Then in your about controller's index method, accept the language var:
Code:
function index($lang = 'en')
{
  // do your stuff
}

But with your approach, you mostly will create a bunch of route configuration list.

You may consider to extending the core language class, then set more general rule. Less seo friendly perhaps, but it will more maintainable and easy to work with than the previous approach.
#3

[eluser]jesusruiz[/eluser]
Thanks for your help, toopay.

I tried the solution given in a reply, but I don't see change in the url. The URL is still: www.site.com/about.html.
This hasn't changed to:
www.site.com/en/about_us.html
or
www.site.com/es/acerca_de.html

I am beginner in CodeIgniter, so I must be doing something bad.
I guess I do not need to use two controllers: about_us (English) and acerca_de (Spanish), because this would be confusing.

I'll keep trying, thank you very much for your reply.


#4

[eluser]Samus[/eluser]
[quote author="jesusruiz" date="1333820994"]Thanks for your help, toopay.

I tried the solution given in a reply, but I don't see change in the url. The URL is still: www.site.com/about.html.
This hasn't changed to:
www.site.com/en/about_us.html
or
www.site.com/es/acerca_de.html

I am beginner in CodeIgniter, so I must be doing something bad.
I guess I do not need to use two controllers: about_us (English) and acerca_de (Spanish), because this would be confusing.

I'll keep trying, thank you very much for your reply.


[/quote]
Try visit www.site.com/en/about_us.html or change those urls in your viewws
#5

[eluser]jesusruiz[/eluser]
Samus, the result is: 404 Page Not Found.
Seems ignore the line added to routes.php.

I'll post my code if you see any errors.

core/My_Config.php
Code:
// Originaly CodeIgniter i18n library by Jérôme Jaglale
// http://maestric.com/en/doc/php/codeigniter_i18n
//modification by Yeb Reitsma

class MY_Config extends CI_Config {

    function site_url($uri = '')
    {    
        if (is_array($uri))
        {
            $uri = implode('/', $uri);
        }
        
        if (function_exists('get_instance'))        
        {
            $CI =& get_instance();
            $uri = $CI->lang->localized($uri);            
        }

        return parent::site_url($uri);
    }
        
}

// END MY_Config Class

/* End of file MY_Config.php */
/* Location: ./application/core/MY_Config.php */


core/My_Lang.php
Code:
<?php (defined('BASEPATH')) OR exit('No direct script access allowed');

// Originaly CodeIgniter i18n library by Jérôme Jaglale
// http://maestric.com/en/doc/php/codeigniter_i18n
// modification by Yeb Reitsma

class MY_Lang extends CI_Lang {


    /**************************************************
     configuration
    ***************************************************/
  
    // languages
    private $languages = array(
        'en' => 'english',
        'es' => 'spanish',
    );
  
    // special URIs (not localized)
    private $special = array (
        "admin"
    );
    
    // where to redirect if no language in URI
    private $uri;
    private $default_uri;
    private $lang_code;
  
    /**************************************************/
    
    
    function MY_Lang()
    {
        parent::__construct();
        
        global $CFG;
        global $URI;
        global $RTR;
        
        $this->uri = $URI->uri_string();
        $this->default_uri = $RTR->default_controller;
        
        $uri_segment = $this->get_uri_lang($this->uri);
        $this->lang_code = $uri_segment['lang'] ;
        
        $url_ok = false;
        if ((!empty($this->lang_code)) && (array_key_exists($this->lang_code, $this->languages)))
        {
            $language = $this->languages[$this->lang_code];
            $CFG->set_item('language', $language);
            $url_ok = true;
        }
        
     if ((!$url_ok) && (!$this->is_special($uri_segment['parts'][0]))) // special URI -> no redirect
     {
      // set default language
      $CFG->set_item('language', $this->languages[$this->default_lang()]);
      
      $uri = (!empty($this->uri)) ? $this->uri: $this->default_uri;
          $uri = ($uri[0] != '/') ? '/'.$uri : $uri;
      $new_url = $CFG->config['base_url'].$this->default_lang().$uri;
      
      header("Location: " . $new_url, TRUE, 302);
      exit;
     }
    }

    
    
    // get current language
    // ex: return 'en' if language in CI config is 'english'
    function lang()
    {
        global $CFG;        
        $language = $CFG->item('language');
        
        $lang = array_search($language, $this->languages);
        if ($lang)
        {
            return $lang;
        }
        
        return NULL;    // this should not happen
    }
    
    
    function is_special($lang_code)
    {
        if ((!empty($lang_code)) && (in_array($lang_code, $this->special)))
            return TRUE;
        else
            return FALSE;
    }
  
  
    function switch_uri($lang)
     {
         if ((!empty($this->uri)) && (array_key_exists($lang, $this->languages)))
         {

          if ($uri_segment = $this->get_uri_lang($this->uri))
          {
           $uri_segment['parts'][0] = $lang;
           $uri = implode('/',$uri_segment['parts']);
          }
          else
          {
           $uri = $lang.'/'.$this->uri;
          }
         }

         return $uri;
     }
    
//check if the language exists
//when true returns an array with lang abbreviation + rest
    function get_uri_lang($uri = '')
    {
     if (!empty($uri))
     {
      $uri = ($uri[0] == '/') ? substr($uri, 1): $uri;
      
      $uri_expl = explode('/', $uri, 2);
      $uri_segment['lang'] = NULL;
      $uri_segment['parts'] = $uri_expl;  
      
      if (array_key_exists($uri_expl[0], $this->languages))
      {
       $uri_segment['lang'] = $uri_expl[0];
      }
      return $uri_segment;
     }
     else
      return FALSE;
    }

    
    // default language: first element of $this->languages
     function default_lang()
{
  $browser_lang = !empty($_SERVER['HTTP_ACCEPT_LANGUAGE']) ? strtok(strip_tags($_SERVER['HTTP_ACCEPT_LANGUAGE']), ',') : '';
  $browser_lang = substr($browser_lang, 0,2);
  return (array_key_exists($browser_lang, $this->languages)) ? $browser_lang: 'en';
}
    
    
    // add language segment to $uri (if appropriate)
    function localized($uri)
    {
     if (!empty($uri))
     {
      $uri_segment = $this->get_uri_lang($uri);
      if (!$uri_segment['lang'])
      {

       if ((!$this->is_special($uri_segment['parts'][0])) && (!preg_match('/(.+)\.[a-zA-Z0-9]{2,4}$/', $uri)))
       {
                 $uri = $this->lang() . '/' . $uri;
                }
            }
     }
        return $uri;
    }
}

// END MY_Lang Class

/* End of file MY_Lang.php */
/* Location: ./application/core/MY_Lang.php */
#6

[eluser]jesusruiz[/eluser]
config/routes.php
Code:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

$route['default_controller'] = "index";
$route['404_override'] = '';
$route['(en|es)/(about_us|acerca_de)'] = "about/$1";

// example: '/en/about' -> use controller 'about'
$route['^en/(.+)$'] = "$1";
$route['^es/(.+)$'] = "$1";

// '/en' and '/es' -> use default controller
$route['^en$'] = $route['default_controller'];
$route['^es$'] = $route['default_controller'];

/* End of file routes.php */
/* Location: ./application/config/routes.php */


controllers/about.php
Code:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class About extends CI_Controller {
    
         public function __construct() {
            parent::__construct();
        }


        public function index()
        {
            $this->lang->load('about');
            if ($this->lang->lang() == "es")
            {
            $data['title'] = 'Acerca de Nosotros';
            $data['main_content'] = '/es/about';
            $this->load->view('template/template',$data);
            }
            else
            {
            $data['title'] = 'About us';
            $data['main_content'] = '/en/about';
            $this->load->view('template/template',$data);  
            }
        }
}


views/en/about.php
Code:
<div id="container">
  &lt;header&gt;
  Cabecera
  &lt;/header&gt;
  <div id="main">
       <section id="main">
    <article>
       Content About us
    </article>
              
       </section>
        
       <aside>
       Content right
       </aside>
  </div>
    
  <footer>
  Footer © Copyright 2012
  </footer>
</div>



This is the current code, although I tried to change the names to view files value, and I get error 404.
#7

[eluser]jesusruiz[/eluser]
I think I've solved it.

The problem was in the following two lines:
Code:
//$route['^en/(.+)$'] = "$1";
//$route['^es/(.+)$'] = "$1";

Deleting them and leaving only those lines:
Code:
$route['default_controller'] = "index";
$route['404_override'] = '';

$route['en/index'] = "index";
$route['es/index'] = "index";

$route['en/prueba_en'] = "about";
$route['es/prueba'] = "about";

// '/en' and '/es' -> use default controller
$route['^en$'] = $route['default_controller'];
$route['^es$'] = $route['default_controller'];

It seems that works OK.

Thanks for the help and best regards.




Theme © iAndrew 2016 - Forum software by © MyBB