您当前的位置: 首页 > 慢生活 > 程序人生 网站首页程序人生
4-6 视图之数据块
发布时间:2023-04-27 19:08:31编辑:雪饮阅读()
-
其实基于上篇,就是说在layout上面还可以调用视图的数据块(如果视图有定义的话),然后在layout上面还可以判断当前所渲染的视图中是否有定义指定数据块。
那么现在假定说有about.php和index.php两个视图,然后我要在index.php中定义数据块block1在about.php中不定义数据块,然后在common.php这个layout中判断当前layout所载入的view是否有定义block1这个数据块,如果有定义则调用出来,如果没有定义则另外渲染一个没有定义数据块的信息。
那么实现如下:
控制器层面就做index.php和about.php两个视图对应的两个操作index和index2:
<?php
namespace app\controllers;
use yii\web\Controller;
class HelloController extends Controller{
public $layout='common';
public function actionIndex(){
return $this->render('index');
}
public function actionIndex2(){
return $this->render('about');
}
}
然后是index.php这个view中定义数据块block1
this is index.php <hr/> <?php $this->beginBlock('block1');?> <h1>我是index.php中定义的block1数据块</h1> <?php $this->endBlock();?>然后是common.php这个layout中判断当前所载入view是否有block1这个数据块根据不同结果来呈现不同的渲染
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>this is common.php</title> </head> <body> <?php if(isset($this->blocks['block1'])):?> <?=$this->blocks['block1'];?> <?php else:?> <h1>当前视图没有数据块</h1> <?php endif;?> <?=$content;?> </body> </html>
关键字词:视图,数据块