Thứ Bảy, 27 tháng 4, 2013

Yii ~ set baseUrl variable in every view, override render function



應該也有人很懶得打

Yii::app() -> request -> baseUrl;

整個就是又臭又長

所以我在Controller.php裡面放了這段

$this -> baseUrl = Yii::app() -> request -> baseUrl;

這樣要baseUrl的時候只要打$this->baseUrl

可是還是覺得很煩...........

因為我比較想打$baseUrl就好

可是這樣在每個view的檔案裏面就要加這段

$baseUrl =  Yii::app() -> request -> baseUrl;

麻煩死0rz

所以乾脆就複寫他原本的render function

讓他每次把data丟進去的時候順便把$baseUrl給設定進去


原本CController.php的render

public function render($view,$data=null,$return=false)
{
if($this->beforeRender($view))
{
$output=$this->renderPartial($view,$data,true);
if(($layoutFile=$this->getLayoutFile($this->layout))!==false)
$output=$this->renderFile($layoutFile,array('content'=>$output),true);

$this->afterRender($view,$output);

$output=$this->processOutput($output);

if($return)
return $output;
else
echo $output;
}
}


在Controller.php裡面加這段function去override

//override
public function render($view, $data = null, $return = false) {
if ($this -> beforeRender($view)) {

$data['baseUrl'] = Yii::app() -> baseUrl;

$output = $this -> renderPartial($view, $data, true);
if (($layoutFile = $this -> getLayoutFile($this -> layout)) !== false)
$output = $this -> renderFile($layoutFile, array('content' => $output), true);

$this -> afterRender($view, $output);

$output = $this -> processOutput($output);

if ($return)
return $output;
else
echo $output;
}
}


Không có nhận xét nào:

Đăng nhận xét