Table of Contents
<?= Html::encode($this->title) ?>
Home Backend Development PHP Tutorial PHP的Yii框架中创建视图和渲染视图的方法详解_PHP

PHP的Yii框架中创建视图和渲染视图的方法详解_PHP

May 28, 2016 am 11:47 AM
php view yii rendering view

视图是 MVC 模式中的一部分。 它是展示数据到终端用户的代码,在网页应用中,根据视图模板来创建视图,视图模板为PHP脚本文件, 主要包含HTML代码和展示类PHP代码,通过yii\web\View应用组件来管理, 该组件主要提供通用方法帮助视图构造和渲染,简单起见,我们称视图模板或视图模板文件为视图。

创建视图

如前所述,视图为包含HTML和PHP代码的PHP脚本,如下代码为一个登录表单的视图, 可看到PHP代码用来生成动态内容如页面标题和表单,HTML代码把它组织成一个漂亮的HTML页面。

<&#63;php
use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $form yii\widgets\ActiveForm */
/* @var $model app\models\LoginForm */

$this->title = 'Login';
&#63;>
<h1 id="Html-encode-this-title"><&#63;= Html::encode($this->title) &#63;></h1>

<p>Please fill out the following fields to login:</p>

<&#63;php $form = ActiveForm::begin(); &#63;>
  <&#63;= $form->field($model, 'username') &#63;>
  <&#63;= $form->field($model, 'password')->passwordInput() &#63;>
  <&#63;= Html::submitButton('Login') &#63;>
<&#63;php ActiveForm::end(); &#63;>

Copy after login

在视图中,可访问 $this 指向 yii\web\View 来管理和渲染这个视图文件。

除了 $this之外,上述示例中的视图有其他预定义变量如 $model, 这些变量代表从控制器或其他触发视图渲染的对象 传入 到视图的数据。

技巧: 将预定义变量列到视图文件头部注释处,这样可被IDE编辑器识别,也是生成视图文档的好方法。
安全

当创建生成HTML页面的视图时,在显示之前将用户输入数据进行转码和过滤非常重要, 否则,你的应用可能会被跨站脚本 攻击。

要显示纯文本,先调用 yii\helpers\Html::encode() 进行转码,例如如下代码将用户名在显示前先转码:

<&#63;php
use yii\helpers\Html;
&#63;>

<div class="username">
  <&#63;= Html::encode($user->name) &#63;>
</div>

Copy after login

要显示HTML内容,先调用 yii\helpers\HtmlPurifier 过滤内容,例如如下代码将提交内容在显示前先过滤:

<&#63;php
use yii\helpers\HtmlPurifier;
&#63;>

<div class="post">
  <&#63;= HtmlPurifier::process($post->text) &#63;>
</div>

Copy after login

技巧:HTMLPurifier在保证输出数据安全上做的不错,但性能不佳,如果你的应用需要高性能可考虑 缓存 过滤后的结果。

组织视图

与 控制器 和 模型 类似,在组织视图上有一些约定:

控制器渲染的视图文件默认放在 @app/views/ControllerID 目录下, 其中 ControllerID 对应 控制器 ID, 例如控制器类为PostController,视图文件目录应为 @app/views/post, 控制器类 PostCommentController对应的目录为@app/views/post-comment, 如果是模块中的控制器,目录应为 yii\base\Module::basePath 模块目录下的views/ControllerID 目录;
对于 小部件 渲染的视图文件默认放在 WidgetPath/views 目录, 其中 WidgetPath 代表小部件类文件所在的目录;
对于其他对象渲染的视图文件,建议遵循和小部件相似的规则。
可覆盖控制器或小部件的 yii\base\ViewContextInterface::getViewPath() 方法来自定义视图文件默认目录。

渲染视图

可在 控制器, 小部件, 或其他地方调用渲染视图方法来渲染视图, 该方法类似以下格式:

/**
 * @param string $view 视图名或文件路径,由实际的渲染方法决定
 * @param array $params 传递给视图的数据
 * @return string 渲染结果
 */
methodName($view, $params = [])
Copy after login

控制器中渲染

在 控制器 中,可调用以下控制器方法来渲染视图:

  • yii\base\Controller::render(): 渲染一个 视图名 并使用一个 布局 返回到渲染结果。
  • yii\base\Controller::renderPartial(): 渲染一个 视图名 并且不使用布局。
  • yii\web\Controller::renderAjax(): 渲染一个 视图名 并且不使用布局, 并注入所有注册的JS/CSS脚本和文件,通常使用在响应AJAX网页请求的情况下。
  • yii\base\Controller::renderFile(): 渲染一个视图文件目录或别名下的视图文件。

例如:

namespace app\controllers;

use Yii;
use app\models\Post;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

class PostController extends Controller
{
  public function actionView($id)
  {
    $model = Post::findOne($id);
    if ($model === null) {
      throw new NotFoundHttpException;
    }

    // 渲染一个名称为"view"的视图并使用布局
    return $this->render('view', [
      'model' => $model,
    ]);
  }
}

Copy after login

小物件
小物件是 CWidget 或其子类的实例.它是一个主要用于表现数据的组件.小物件通常内嵌于一个视图来产生一些复杂而独立的用户界面.例如,一个日历小物件可用于渲染一个复杂的日历界面.小物件使用户界面更加可复用.

我们可以按如下视图脚本来使用一个小物件:

<&#63;php $this->beginWidget('path.to.WidgetClass'); &#63;>
...可能会由小物件获取的内容主体...
<&#63;php $this->endWidget(); &#63;>
Copy after login

或者

<&#63;php $this->widget('path.to.WidgetClass'); &#63;>
Copy after login

后者用于不需要任何 body 内容的组件.

小物件可通过配置来定制它的表现.这是通过调用 CBaseController::beginWidget 或 CBaseController::widget 设置其初始化属性值来完成的.例如,当使用 CMaskedTextField 小物件时,我们想指定被使用的 mask (可理解为一种输出格式,译者注).我们通过传递一个携带这些属性初始化值的数组来实现.这里的数组的键是属性的名称,而数组的值则是小物件属性所对应的值.正如以下所示 :

<&#63;php
$this->widget('CMaskedTextField',array(
  'mask'=>'99/99/9999'
));
&#63;>
Copy after login

继承 CWidget 并覆盖其init() 和 run() 方法,可以定义一个新的小物件:

class MyWidget extends CWidget
{
  public function init()
  {
    // 此方法会被 CController::beginWidget() 调用
  }
 
  public function run()
  {
    // 此方法会被 CController::endWidget() 调用
  }
}
Copy after login

小物件可以像一个控制器一样拥有它自己的视图.默认情况下,小物件的视图文件位于包含了小物件类文件目录的 views 子目录之下.这些视图可以通过调用 CWidget::render() 渲染,这一点和控制器很相似.唯一不同的是,小物件的视图没有布局文件支持。另外,小物件视图中的$this指向小物件实例而不是控制器实例。

视图中渲染

可以在视图中渲染另一个视图,可以调用yii\base\View视图组件提供的以下方法:

  • yii\base\View::render(): 渲染一个 视图名.
  • yii\web\View::renderAjax(): 渲染一个 视图名 并注入所有注册的JS/CSS脚本和文件,通常使用在响应AJAX网页请求的情况下。
  • yii\base\View::renderFile(): 渲染一个视图文件目录或别名下的视图文件。

例如,视图中的如下代码会渲染该视图所在目录下的 _overview.php 视图文件, 记住视图中 $this 对应 yii\base\View 组件:

<&#63;= $this->render('_overview') &#63;>
Copy after login

其他地方渲染

在任何地方都可以通过表达式 Yii::$app->view 访问 yii\base\View 应用组件, 调用它的如前所述的方法渲染视图,例如:

// 显示视图文件 "@app/views/site/license.php"
echo \Yii::$app->view->renderFile('@app/views/site/license.php');
Copy after login

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles