Yii2框架视图(View)操作及Layout的使用方法分析

时间:2022-07-27
本文章向大家介绍Yii2框架视图(View)操作及Layout的使用方法分析,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本文实例讲述了Yii2框架视图(View)操作及Layout的使用方法。分享给大家供大家参考,具体如下:

渲染视图

1.我们在Default 控制器里做演示

<?php
namespace appcontrollers;
use yiihelpersUrl;
use yiiwebController;
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 yiihelpersHtml::encode($username); ? </p 
<p <?php echo yiihelpersHtml::encode($age); ? </p 

布局layout

1.默认布局

yiibaseApplication::$layout = 'main'
appmoduleadminModule::$layout = 'main';

this- layout = false。 也可以使用this- renderPartial()代替this- render()

2.新建布局

View/layout/default.php

我们要在Default控制器里使用这个布局,写上:

public $layout = 'default';

浏览器效果: