12.Yii2.0框架视图模版继承与模版相互调用


模板渲染的两种方式

1441611-20180903100459521-409733611.png

加载视图 index.php 和 about.php 页面

建立控制器HomeController php

D:\phpStudy\WWW\yii\controllers\HomeController.php

<?php
/**
 * Created by Haima.
 * Author:Haima
 * QQ:228654416
 * Date: 2018/9/3
 * Time: 10:30
 */

namespace app\controllers;

use yii\base\Controller;

class HomeController extends Controller
{
    public function actionIndex()
    {
        //会自动加载父模板 D:\phpStudy\WWW\yii\views\layouts\main.php
        return $this->render('index');
    }

    public function actionAbout()
    {
        //不会自动加载父模板
        return $this->renderpartial('about');
    }
}

新建模板 home\index.php

D:\phpStudy\WWW\yii\views\home\index.php

<h2>index</h2>

访问效果(会自动加载父模板):
1441611-20180903103603700-1508251081.png

D:\phpStudy\WWW\yii\views\home\about.php

<h2>about</h2>

新建模板home\about.php

访问效果(不会自动加载父模板):
1441611-20180903104618023-172662187.png


模板继承属性与视图的相互调用

1441611-20180903101754076-1404703418.png

建立控制器HomeController php.

D:\phpStudy\WWW\yii\controllers\HomeController.php

<?php
/**
 * Created by Haima.
 * Author:Haima
 * QQ:228654416
 * Date: 2018/9/3
 * Time: 10:30
 */

namespace app\controllers;

use yii\base\Controller;

class HomeController extends Controller
{
    //用属性的方法定义父模板
    //会自动加载D:\phpStudy\WWW\yii\views\layouts\home.php文件
    public $layout = 'home';
    public function actionIndex()
    {
        //会自动加载父模板 D:\phpStudy\WWW\yii\views\layouts\home.php
        return $this->render('index');
    }

    public function actionAbout()
    {
        //会自动加载D:\phpStudy\WWW\yii\views\layouts\home.php文件
        return $this->render('about');
        //不会自动加载父模板
        // return $this->renderpartial('about');
    }
}

新建home.php父级模板

D:\phpStudy\WWW\yii\views\layouts\home.php

<!DOCTYPE html>
<html>
<head>
    <title>home</title>
</head>
<body>
<h1>this ihs home.php</h1>
<?=$content?> <!-- 创建可编辑区域 -->
</body>
</html>

新建模板 home\about.php

D:\phpStudy\WWW\yii\views\home\about.php

<h2>about</h2>

访问效果:
1441611-20180903111118540-1686947404.png


新建模板 home\index.php

D:\phpStudy\WWW\yii\views\home\index.php

<h2>index</h2>
<?=$this->render('about');?> <!-- 加载调用同级里的about模板 -->

访问效果:
1441611-20180903111243803-476995236.png

转载于:https://www.cnblogs.com/haima/p/9577087.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值