Welcome Guest, Not a member yet? Register   Sign In
internationalization - routing - language code on URLs
#1

(This post was last modified: 06-09-2015, 01:50 PM by Guido. Edit Reason: bugfix :) )

Hi,
here I share an idea that worked for me (it seems to work) when trying to handle i18n on routes with CI.

No core classes extension required, no third party extensions, just routing config. Controller classes must read the constant URI_LOCALE which is defined on every request.

URL's looks like this: http://localhost/en-US/your_route...

Added this code in /application/config/routes.php:

Code:
// Define your locale format: en-US, es-AR, etc
define('LOCALE_FORMAT', '([a-z|A-Z]{2}-[a-z|A-Z]{2})');

// Sets the URI_LOCALE constant required for localization to be read by Controllers
function handle_locale($locale, $route='')
{
    define('URI_LOCALE', $locale);
    return $route;
};

// Localized default controller
$route[LOCALE_FORMAT] = function ($locale) { return handle_locale($locale); };

// Simple route
//$route['logout'] = '/login/logout';  // Non-localized, just a example (not required)
$route[LOCALE_FORMAT . '/logout'] = function ($locale, $route='/login/logout') { return handle_locale($locale, $route); };

// Wildcard example
// $route['product/(:num)'] = 'catalog/product_lookup_by_id/$1'; // Non-localized, just a example extracted from CI user guide (not required)
$route[LOCALE_FORMAT . '/catalog/(:num)'] = function ($locale, $var1)
{
    $route = 'catalog/product_lookup_by_id/' . $var1;
    return handle_locale($locale, $route);
};

// RegEx example
//$route['products/([a-z]+)/(\d+)'] = '$1/id_$2'; // Non-localized, just a example extracted from CI user guide (not required)
$route[LOCALE_FORMAT . '/products/([a-z]+)/(\d+)'] = function ($locale, $var1, $var2)
{
    $route = $var1 . '/id_' . $var2;
    return handle_locale($locale, $route);
};

// All other localized routes: put this always at the end
$route[LOCALE_FORMAT . '/(.+)$'] = function ($locale, $route) { return handle_locale($locale, $route); };

Give it a try if you wish...

regards.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB