个性化阅读
专注于IT技术分析

YII视图介绍和用法示例

点击下载

本文概述

MVC结构中的视图部分负责在用户面前呈现数据。它们主要包含HTML内容和演示PHP代码。


创建视图

查看基本Yii页面的关于页面代码。

<?php 

/* @var $this yii\web\View */ 

use yii\helpers\Html; 

$this->title = 'About'; 
$this->params['breadcrumbs'][] = $this->title; 
?> 
<div class="site-about"> 
    <h1><?= Html::encode($this->title) ?></h1> 

    <p>This is the About page. You may modify the following file to customize its content:</p> 

    <code><?= __FILE__ ?></code> 
</div>

它的输出是这样的:

YII Views 1

在上面的脚本中, PHP代码用于在title和form标记内部生成动态内容。 HTML标签在演示视图中显示数据。


视图约定

  • 控制器渲染的视图应写入@ app / views / controllerID文件夹。
  • 由窗口小部件呈现的视图应写入widgetPath / views文件夹。

可以调用以下控制器方法来呈现控制器内的视图:

  • render():渲染提到的视图文件并应用布局。
  • renderPartial():渲染提到的视图, 但不应用布局。
  • renderAjax():渲染一个没有布局的视图, 并注入所有注册的JS脚本和CSS文件。
  • renderFile():在指定的路径中渲染视图文件。
  • renderContent():渲染静态环。

可以调用以下控制器方法来在另一个视图中呈现视图:

  • render():渲染视图页面。
  • renderAjax():渲染一个没有布局的视图, 并注入所有注册的JS脚本和CSS文件。
  • renderFile():在指定的路径中渲染视图文件。

可以调用以下控制器方法在小部件内呈现视图:

  • render():渲染视图页面。
  • renderFile():在指定的路径中渲染视图文件。

例:

步骤1在views / site文件夹内, 我们正在创建一个视图文件exm.php文件。

<!DOCTYPE html> 
<html> 
<head> 
	<title></title> 
</head> 
<body> 
	<h1>Hello, welcome to srcmini.</h1> 
</body> 
</html>

步骤2在site文件夹的about.php视图文件中渲染exm.php视图文件。

<?php 

/* @var $this yii\web\View */ 

use yii\helpers\Html; 

$this->title = 'About'; 
$this->params['breadcrumbs'][] = $this->title; 
?> 
<div class="site-about"> 
    <h1><?= Html::encode($this->title) ?></h1> 

    <p>This is the About page. You may modify the following file to customize its content:</p> 

     <?= $this->render("exm") ?> 

    <code><?= __FILE__ ?></code> 
</div>

步骤3在浏览器上运行它。

YII Views 2
赞(0)
未经允许不得转载:srcmini » YII视图介绍和用法示例

评论 抢沙发

评论前必须登录!