简体   繁体   中英

How to change CodeIgniter's URI segments based on a language

Question:
How could I make my URL language specific, for example:

  • English
    www.website.com / controller-in-en / method-in-en
  • Other language
    www.website.com / controller-in-oth-lang / method-in-oth-lang
    (I want this URL to be automatically redirected to www.website.com / controller-in-en / method-in-en based on a 'controller-in-en' and 'method-in-en' translation in a language file).

Additional information:
In the future, I plan to redirect users for different languages to different subdomains, eg lt.website.com, but right now I want URI segments to be translated depending on users language.

I want to make clear that:

  1. I already know how to create a language switcher and change language.
  2. I DO NOT want language code to be included in the url, like '/en' or '/lt'.

My (bad) ideas:
I thought this could be done via translated routing addresses $route[lang('url_market')] = 'market/index'; but when routing is done, language library is not yeat loaded.

Based On @AdrienXL answer, Here's a sample without using a database.

$config['routes_translation']['en'] = array(
'home' => 'home'
);

$config['routes_translation']['fr'] = array(
'home' => 'accueil'
);

Obviously, You know the language for the user using a session, And you have the controller name, You can get the translation easily by accessing the config item.

$translatedNamed = $config['routes_translation'][$language_code][$controller] 

which should give you 'home' for en & 'accueil' for fr

The only way I see is through the db.

Build a table that looks like this :

routes_translation

*****************************************
*id |  controller   | translation | lang*
*****************************************
* 1 | home          |    home     | en  *
* 2 | home          |  accueil    | fr  *
                   ...
*****************************************

Then in your routes.php

require_once( BASEPATH .'database/DB'. EXT );
$db =& DB();
$query = $db->get('routes_translation');
$result = $query->result();
foreach( $result as $row )
{
    $route[$row->translation] = $row->controller;
} 

Simple....

  1. Get the user select language either from db or store it in SESSION
  2. Pass the selected laguage while loading the language library

Eg: $this->lang->load("message",$SESSION['selected_language']);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM