Yii框架视图、视图布局、视图数据块操作示例

时间:2022-07-27
本文章向大家介绍Yii框架视图、视图布局、视图数据块操作示例,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文实例讲述了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 yiihelpersHtml;
  use yiihelpersHtmlPurifier;
? 
<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框架的PHP程序设计有所帮助。