//在視圖輸出一個(gè)“hello world”字串 //controllers目錄下創(chuàng)建一個(gè)HelloController,控制器的名字里要求用Controller結(jié)尾,首字母大寫(xiě) class HelloController extends Controller{ public function actionIndex(){ //渲染一個(gè)視圖 $this->render('index'); } } //在視圖目錄views下創(chuàng)建一個(gè)hello/index.php的文件,在文件里面輸出hello world! <?php echo 'hello world'; ?>
//我們進(jìn)入render方法看看 public function render($view,$data=null,$return=false) { //調(diào)用render前的鉤子,在調(diào)用視圖前的特殊處理邏輯可以在beforeRender里實(shí)現(xiàn) if($this->beforeRender($view)) { //先獲取renderPartial的輸出結(jié)果,renderPartial是局部渲染,直接在action里調(diào)用效果如圖2 $output=$this->renderPartial($view,$data,true); //獲取頭尾部文件,這里是通過(guò)controller的layout屬性來(lái)指定的 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; } } ![]() // render是可以帶參數(shù)的 //比如controller中定義一個(gè)變量$str public function actionIndex(){ $str = 'hello,world!'; //渲染一個(gè)視圖 $this->render('index',array( 'str'=>$str, )); // $this->renderPartial('index'); }//視圖view中直接輸出 <?php echo 'hello world'; echo '<br />'; echo $str; ?>// 視圖中的$this是當(dāng)前的控制器對(duì)象 //視圖中可以用$this去調(diào)用controller的屬性或者方法 <?php //調(diào)用控制器的屬性 echo $this->id; echo '<br />'; echo $this->action->id; echo '<br />'; echo $this->layout; echo '<br />'; //調(diào)用控制器里的方法 echo $this->createUrl('site/index'); ?> |
|