//在视图输出一个“hello world”字串 //controllers目录下创建一个HelloController,控制器的名字里要求用Controller结尾,首字母大写 class HelloController extends Controller{ public function actionIndex(){ //渲染一个视图 $this->render('index'); } } //在视图目录views下创建一个hello/index.php的文件,在文件里面输出hello world! <?php echo 'hello world'; ?>
//我们进入render方法看看 public function render($view,$data=null,$return=false) { //调用render前的钩子,在调用视图前的特殊处理逻辑可以在beforeRender里实现 if($this->beforeRender($view)) { //先获取renderPartial的输出结果,renderPartial是局部渲染,直接在action里调用效果如图2 $output=$this->renderPartial($view,$data,true); //获取头尾部文件,这里是通过controller的layout属性来指定的 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是可以带参数的 //比如controller中定义一个变量$str public function actionIndex(){ $str = 'hello,world!'; //渲染一个视图 $this->render('index',array( 'str'=>$str, )); // $this->renderPartial('index'); }//视图view中直接输出 <?php echo 'hello world'; echo '<br />'; echo $str; ?>// 视图中的$this是当前的控制器对象 //视图中可以用$this去调用controller的属性或者方法 <?php //调用控制器的属性 echo $this->id; echo '<br />'; echo $this->action->id; echo '<br />'; echo $this->layout; echo '<br />'; //调用控制器里的方法 echo $this->createUrl('site/index'); ?> |
|