Part of the EllisLab Network
x
 
Create New Page
 View Previous Changes    ( Last updated by {author} )

Revision: Category:Internationalization -> Internationalization Views i18n

Revision from: 03:23, 25 Nov 2006

Category:Internationalization -> Internationalization Views i18n
[h1]Adding internationalization for views[/h1]
By extending the Controller it is possible to easily add multilingual support for your Controllers when calling views, the example described here allows urls to be used to identify the users language and is especially useful for views that have a large amount of static content which is language specific.

It works by identifying the language from the url and then when loading the view looks for a view with the language extension first and if it is not found then looks for the specified view for example:

http://www.example.com/it/... and looks for view_name_it.php then view_name.php
http://www.example.com/fr/... and looks for view_name_fr.php  then view_name.php
http://www.example.com/fr/... and looks for view_name_de.php  then view_name.php

This is achieved by calling $this->load_view instead of $this->load->view in your controller

The whole process takes four steps
1. Modify your config.php & .htaccess files
2. Add controller to manage langauge identification and load correct view
3. Add helper helper with similar functions to url_helper
4. Create multi-lingual views

1. Modify your config.php & routes.php files

Firstly add the following line to your config.php file

$config['lang_code'] = "en";


here i have specified english (en) as the default language code.

The set up the routes for the different language your application will support an example is shown below:

$route['it'] = "welcome";
$route['^it/(.+)$'] = "$1";

2. Add controller i18n to manage language loading of views

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

class
i18n extends Controller {
    
  
var $lang_code;
  
// Change the values to obtain the languages your require
  
var $languages = array('english' => 'en',
                          
'italian' => 'it',
                          
'german' => 'de',
                          
'french' => 'fr',
                          
'spanish' => 'es',
                          
'japanese' => 'jp',
                          );
  
  
/**
   * i18n
   *
   * Identifies the user language and stores the correct code
   */
  
function i18n ()
  
{
    parent
::Controller();
    
$this->load->helper('url_i18n');
    if (
$this->uri->segment(1))
    
{
      $this
->lang_code = $this->_identify_language($this->uri->segment(1));
    
}
    
else
    
{
      $this
->lang_code = $this->config->item('lang_code');
    
}
  }
  
/**
  * Load View (same as $this->load->view()
  *
  * This function is used to load a "view" file.  It has three parameters:
  *
  * 1. The name of the "view" file to be included.
  * 2. An associative array of data to be extracted for use in the view.
  * 3. TRUE/FALSE - whether to return the data or load it.  In
  * some cases it's advantageous to be able to return data so that
  * a developer can process it in some way.
  *
  * @access    public
  * @param    string
  * @param    array
  * @param    bool
  * @return    void
  */
  
function load_view($view, $vars = array(), $return = FALSE)
  
{   
    
if (file_exists(APPPATH.'views/'.$view.'_'.$this->lang_code.EXT))
    
{
      
// Use language specific template
      
return $this->load->view($view.'_'.$this->lang_code, $vars, $return);
    
}
    
// Language specific template not found use default
    
return $this->load->view($view, $vars, $return);
  
}
  
  
/**
   * @access    private
   * @param string
   * @return    void
   */
  
function _identify_language($str = '')
  
{
    
foreach($this->languages as $language => $code)
    
{
      
if ($str == $code)
        return
$code;
    
}
    
// Reach here and the default language is used (declared in config/config.php)
    
return $this->config->item('lang_code');
  
}
  
}
?>

3. Add url helper which can also manage different languages

This helper has identical functions to the CI url_helper but the language code is passed to ensure the correct urls are created.  All the functions have the same name with _i18n appended on the end and the last parameter is the language code.

/**
* Site URL
*
* Create a local URL based on your basepath. Segments can be passed via the
* first parameter either as a string or an array.
*
* @access    public
* @param    string
* @return    string
*/    
function site_url_i18n($uri = '', $lang_code = '')
{
    $CI
=& get_instance();
    if (
$lang_code)
    
{
        
return $CI->config->site_url($lang_code.'/'.$uri);
    
}
    
else
    
{
        
return $CI->config->site_url($uri);
    
}
}

    
// ------------------------------------------------------------------------

/**
* Anchor Link
*
* Creates an anchor based on the local URL.
*
* @access    public
* @param    string    the URL
* @param    string    the link title
* @param    mixed    any attributes
* @return    string
*/    
function anchor_i18n($uri = '', $title = '', $attributes = '', $lang_code = '')
{
  
  
if ( ! is_array($uri))
    
{
        $site_url
= ( ! preg_match('!^\w+://!i', $uri)) ? site_url_i18n($uri, $lang_code) : $uri;
    
}
    
else
    
{
        $site_url
= site_url_i18n($uri, $lang_code);
    
}
    
    
if ($title == '')
    
{
        $title
= $site_url;
    
}

    
if ($attributes == '')
    
{
        $attributes
= ' title="'.$title.'"';
    
}
    
else
    
{
        $attributes
= _parse_attributes_i18n($attributes);
    
}

    
return '';
    
}
    
    
if ( ! is_array($attributes))
    
{
        $attributes
= array();
    
}
        
    
foreach (array('width' => '800', 'height' => '600', 'scrollbars' => 'yes', 'status' => 'yes', 'resizable' => 'yes', 'screenx' => '0', 'screeny' => '0', ) as $key => $val)
    
{
        $atts[$key]
= ( ! isset($attributes[$key])) ? $val : $attributes[$key];
    
}

    
return "";
}
    
    
// ------------------------------------------------------------------------

/**
* Header Redirect
*
* Header redirect in two flavors
*
* @access    public
* @param    string    the URL
* @param    string    the method: location or redirect
* @return    string
*/
function redirect_i18n($uri = '', $method = 'location', $lang_code = '')
{
    
switch($method)
    
{
        
case 'refresh' : header("Refresh:0;url=".site_url_i18n($uri, $lang_code));
            break;
        default        :
header("location:".site_url_i18n($uri, $lang_code));
            break;
    
}
    
exit;
}

/**
* Parse out the attributes
*
* Some of the functions use this
*
* @access    private
* @param    array
* @param    bool
* @return    string
*/
function _parse_attributes_i18n($attributes, $javascript = FALSE)
{
    
if (is_string($attributes))
    
{
        
return ($attributes != '') ? ' '.$attributes : '';
    
}

    $att
= '';
    foreach (
$attributes as $key => $val)
    
{
        
if ($javascript == TRUE)
        
{
            $att
.= $key . '=' . $val . ',';
        
}
        
else
        
{
            $att
.= ' ' . $key . '="' . $val . '"';
        
}
    }
    
    
if ($javascript == TRUE AND $att != '')
    
{
        $att
= substr($att, 0, -1);
    
}
    
    
return $att;
}

4. Create your views

The views are stored together and each view has their code attached to the end .
default_view.php     Default language view
default_view_es.php     Spanish language view
default_view_fr.php     French language view

Example controller

Here is an example controller whch, has only one view and function call.
It is important to note the call to load the view is $this->load_view(‘legal/copyright_view’, ‘’, true)) and not
$this->load->view(‘legal/copyright_view’, ‘’, true)).  This change enables the correct view to be loaded

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

//Remember to include this
require_once('i18n.php');

class
Legal extends i18n {
    
  
function Legal()
  
{
    parent
::i18n();
  
}
  
  
/**
   * Display copyright
   */
  
function index()
  
{    
    $this
->set_section('title', 'Copyright');
    
$this->set_section('contents', $this->load_view('legal/copyright_view', '', true));
  
}
}

Categories: