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

吾爱主题 阅读:145 2021-09-02 16:53:00 评论:0

本文实例讲述了Yii框架视图、视图布局、视图数据块操作。分享给大家供大家参考,具体如下:

Yii 视图

控制器方法代码:

?
1 2 3 4 5 6 7 8 9 public function actionIndex(){    $data = array (      'name' => 'zhangsan' ,      'age' => 12,      'address' => array ( '北京市' , '朝阳区' ),      'intro' => '我是简介,<script>alert("123");</script>'    );    return $this ->renderPartial( 'index' , $data ); //第二个参数赋值 }

视图代码:

?
1 2 3 4 5 6 7 8 9 10 <?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 视图布局

控制器代码:

?
1 2 3 4 5 6 7 //设置的布局文件   public $layout = 'common' ;   public function actionAbout(){     $data = array ( 'page_name' => 'About' );     //render方法会把视图文件common的内容放到$content当中,并显示布局文件。     return $this ->render( 'about' , $data );   }

公共视图common代码:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 <!DOCTYPE html> <html> <head>    <title></title>    <meta charset= "UTF-8" > </head> <body> <h1>这是Common内容</h1> <div>    <?= $content ?> </div> </body> </html>

视图about代码,并调用了activity视图:

?
1 2 <h1> Hello <?= $page_name ?></h1> <?php echo $this ->render( 'activity' , array ( 'page_name' => 'activity' ));?>

视图activity代码:

?
1 <h1> Hello <?= $page_name ?></h1>

结论:视图引用了公共布局文件,并且在一个视图中调用另一个视图文件。

Yii 视图数据块

控制器代码:

?
1 2 3 4 5 6 7 8 9 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代码:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 <!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代码:

?
1 2 3 4 <?php $this ->beginBlock( 'webTitle' );?> <?= $page_name ?>页面 <?php $this ->endBlock();?> <h1> Hello <?= $page_name ?></h1>

视图teacher代码:

?
1 2 3 4 <h1> Hello <?= $page_name ?></h1> <?php $this ->beginBlock( 'webTitle' );?> <?= $page_name ?>页面 <?php $this ->endBlock();?>

总结:如果需要在视图中改变公共模板中的内容,需要使用block方法,例如上面例子中改变了common页面的title。

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

原文链接:https://www.cnblogs.com/gyfluck/p/9100573.html

可以去百度分享获取分享代码输入这里。
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

【腾讯云】云服务器产品特惠热卖中
搜索
标签列表
    关注我们

    了解等多精彩内容