本文实例讲述了Yii2框架视图(View)操作及Layout的使用方法。分享给大家供大家参考,具体如下:
渲染视图
1.我们在Default 控制器里做演示
<?phpnamespace app/controllers;use yii/helpers/Url;use yii/web/Controller;class DefaultController extends Controller{ public function actionIndex() {// echo Url::toRoute(['index','id'=>11],true);// //http://localhost/yiipro/web/default/index?id=11//// echo Url::base();// ///yiipro/web // 返回视图 return $this->render('index'); }}
return $this->render('index');
就是渲染视图
2.浏览器访问http://localhost/yiipro/web/index.php/default/,发现报错了

views/default/index.php
说明视图文件要放在views/default 目录下。
我们去创建视图

再次访问:

3.如何向视图传递变量
return $this->render('index',['username'=>'张三','age'=>22]);
<p><?php echo /yii/helpers/Html::encode($username); ?></p><p><?php echo /yii/helpers/Html::encode($age); ?></p>

布局layout
1.默认布局

yii/base/Application::$layout = 'main'app/module/admin/Module::$layout = 'main';
不使用layout,在控制器中加入属性public $layout = false
或方法中动态修改$this->layout = false
。
也可以使用$this->renderPartial()
代替$this->render()
2.新建布局
View/layout/default.php

我们要在Default控制器里使用这个布局,写上:
public $layout = 'default';
浏览器效果:

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。
注:相关教程知识阅读请移步到PHP教程频道。