Multiple languages in cakephp using 2-letter instead of 3-letter in URL
I am putting together a multilingual site according to the tutorial: http://nuts-and-bolts-of-cakephp.com/2008/11/28/cakephp-url-based-language-switching-for-i18n-and-l10n-internationalization-and-localization/
However, the tutorial uses three letter notation for different languages (eng
, rus
) and I would like to use two letters only.
I changed config/core.php
Configure::write('Config.language', 'en');
then also config/routes.php
Router::connect('/:language/:controller/:action/*', array(), array('language' => '[a-z]{2}'));
and also the path to:
locale/en/LC_MESSAGES/default.po
locale/ru/LC_MESSAGES/default.po
but it is still not working. Strings turn out as their default and not read from the .po
files.
The .po
files, i got from runing cake i18n to generate one single .pot
file that i then renamed to .po
and copied in each directory for each language.
the .po
files are utf-8 encoded.
i also have in my config/bootstrap.php
:
Configure::write('Config.languages', array(
'en' => array(
'language' => 'English',
'locale' => 'en',
'localeFallback' => 'en',
'charset' => 'utf-8'
),
'bg' =&开发者_C百科gt; array(
'language' => 'Bulgarian',
'locale' => 'bg',
'localeFallback' => 'bg',
'charset' => 'utf-8'
),
)
);
What am i missing?
You don't have to change the i18n internals just to change how the URLs look like. Leave everything else alone except the route configuration and at the start of _setLanguage()
function convert the 2-letter language codes to 3-letter codes. (_setLanguage()
being the function mentioned in the tutorial you linked to.)
For example, if you know that you'll be supporting only 2-3 languages it's easiest to do the conversion manually:
function _setLanguage() {
if ($this->Cookie->read('lang') && !$this->Session->check('Config.language')) {
$this->Session->write('Config.language', $this->Cookie->read('lang'));
}
else if (isset($this->params['language']) && ($this->params['language']
!= $this->Session->read('Config.language'))) {
// ADD THIS
switch( $this->params['language'] ) {
case 'bg':
$lang = 'bul';
break;
case 'en':
default:
$lang = 'eng';
break;
}
$this->Session->write('Config.language', $lang);
$this->Cookie->write('lang', $lang, false, '20 days');
}
}
Now everything will work using 3-letter language codes under the hood but you can provide 2-letter codes to the user.
I find very interesting also the possibility to AUTO discover user's browser lang.
You may add an additional option this way:
...
}elseif(isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])){
if (ereg("bg", $_SERVER["HTTP_ACCEPT_LANGUAGE"]))
$lang = 'bul';
if (ereg("en", $_SERVER["HTTP_ACCEPT_LANGUAGE"]))
$lang = 'eng';
}
精彩评论