本文实例讲述了Yii框架视图、视图布局、视图数据块操作。分享给大家供大家参考,具体如下:
Yii 视图
控制器方法代码:
public function actionIndex(){ $data = array( 'name' => 'zhangsan', 'age' => 12, 'address' => array('北京市','朝阳区'), 'intro' => '我是简介,<script>alert("123");</script>' ); return $this->renderPartial('index',$data);//第二个参数赋值 }
视图代码:
<?php use yii\helpers\Html; use yii\helpers\HtmlPurifier; ?> <h1>Hello index view</h1> <h2>姓名:<?php echo $name;?></h2> <h2>年龄:<?=$age?></h2> <h2>地址:<?=$address[0]?> <?=$address[1]?></h2> <h2>简介:<?=Html::encode($intro)?> </h2> <h2>简介:<?=HtmlPurifier::process($intro)?> </h2>
Yii 视图布局
控制器代码:
//设置的布局文件 public $layout = 'common'; public function actionAbout(){ $data = array('page_name'=>'About'); //render方法会把视图文件common的内容放到$content当中,并显示布局文件。 return $this->render('about',$data); }
公共视图common代码:
<!DOCTYPE html> <html> <head> <title></title> <meta charset="UTF-8"> </head> <body> <h1>这是Common内容</h1> <div> <?=$content?> </div> </body> </html>
视图about代码,并调用了activity视图:
<h1> Hello <?=$page_name?></h1> <?php echo $this->render('activity',array('page_name'=>'activity'));?>
视图activity代码:
<h1> Hello <?=$page_name?></h1>
结论:视图引用了公共布局文件,并且在一个视图中调用另一个视图文件。
Yii 视图数据块
控制器代码:
public $layout = 'common'; public function actionStudent(){ $data = array('page_name'=>'Student'); return $this->render('student',$data); } public function actionTeacher(){ $data = array('page_name'=>'Teacher'); return $this->render('teacher',$data); }
公共布局文件common代码:
<!DOCTYPE html> <html> <head> <title> <?php if(isset($this->blocks['webTitle'])):?> <?=$this->blocks['webTitle'];?> <?php else:?> commom <?php endif;?> </title> <meta charset="UTF-8"> </head> <body> <h1>这是Common内容</h1> <div> <?=$content?> </div> </body> </html>
视图student代码:
<?php $this->beginBlock('webTitle');?> <?=$page_name?>页面 <?php $this->endBlock();?> <h1> Hello <?=$page_name?></h1>