我終於有了我的多語言CakePHP 2.1應用程序幾乎可以工作。CakePHP 2.1 URL語言參數
首先,我定義爲core.php
年底的默認語言:
/* Define default language */
Configure::write('Config.language', 'eng');
這是我在AppControler.php
代碼:
public function beforeFilter() {
parent::beforeFilter();
$this->_setLanguage();
//Configure::write('Config.language', 'fre'); //Manually change the language to test .po file
$this->Auth->allow('index','view','home','display','logout');
}
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'))) {
$this->Session->write('Config.language', $this->params['language']);
$this->Cookie->write('lang', $this->params['language'], false, '20 days');
}
}
如果我在AppController.php取消註釋Configure::write('Config.language', 'fre');
,整個網站是法語的(除了數據庫驅動的內容,我打算使用TranslateBehavior)。但是,我想在點擊按鈕時使用基於URL的語言切換,這就是應用程序崩潰的地方。這裏是我的路線,在此基礎上nuts-and-bolts tutorial:
Router::connect('/:language/:controller/:action/*', array(), array('language' => '[a-z]{2}'));
這裏是我的按鈕代碼:
<?php echo $this->Html->link($this->Html->image('../img/PUZ013-US-Flag.png', array('border' => '0')),array('language'=>'eng'),array('target' => '_parent', 'escape' => false));;?>  <?php echo $this->Html->link($this->Html->image('../img/PUZ013-FR-Flag.png', array('border' => '0')),array('language'=>'fre'),array('target' => '_parent', 'escape' => false));?>
我有這樣的AppHelper處理URL轉換,但它不工作。 URL應該是example.com/fre/controller/action,但是它是example.com/controller/action/language:fre,並且cookie不會改變。
class AppHelper extends Helper {
public function url($url = null, $full = false) {
if(!isset($url['language']) && isset($this->params['language'])) {
$url['language'] = $this->params['language'];
}
return parent::url($url, $full);
}
}
如果你點擊標誌,什麼都不會發生。我錯過了什麼?
謝謝,這幫助寫! 'fre'正在加載它現在應該加載的位置,但它正在檢查FreController而不是將fre視爲語言參數。 – deewilcox 2012-04-13 14:00:45