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

[TOC]

模板渲染的两种方式

##加载视图 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>

访问效果(会自动加载父模板):

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

<h2>about</h2>

新建模板home\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
{
    //用属性的方法定义父模板
    //会自动加载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>

访问效果:


新建模板 home\index.php

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

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

访问效果:

posted @   HaimaBlog  阅读(909)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示