本文實例講述了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>
視圖teacher代碼:
h1> Hello ?=$page_name?>/h1> ?php $this->beginBlock('webTitle');?> ?=$page_name?>頁面 ?php $this->endBlock();?>
總結:如果需要在視圖中改變公共模板中的內容,需要使用block方法,例如上面例子中改變了common頁面的title。
更多關于Yii相關內容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結》、《php優秀開發框架總結》、《smarty模板入門基礎教程》、《php面向對象程序設計入門教程》、《php字符串(string)用法總結》、《php+mysql數據庫操作入門教程》及《php常見數據庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。