PHP的Yii框架中创建视图和渲染视图的方法详解,yii框架
PHP的Yii框架中创建视图和渲染视图的方法详解,yii框架
视图是 MVC 模式中的一部分。 它是展示数据到终端用户的代码,在网页应用中,根据视图模板来创建视图,视图模板为PHP脚本文件, 主要包含HTML代码和展示类PHP代码,通过yii\web\View应用组件来管理, 该组件主要提供通用方法帮助视图构造和渲染,简单起见,我们称视图模板或视图模板文件为视图。
创建视图
如前所述,视图为包含HTML和PHP代码的PHP脚本,如下代码为一个登录表单的视图, 可看到PHP代码用来生成动态内容如页面标题和表单,HTML代码把它组织成一个漂亮的HTML页面。
<?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'; ?> <h1 id="Html-encode-this-title"><?= Html::encode($this->title) ?></h1> <p>Please fill out the following fields to login:</p> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'username') ?> <?= $form->field($model, 'password')->passwordInput() ?> <?= Html::submitButton('Login') ?> <?php ActiveForm::end(); ?>
在视图中,可访问 $this 指向 yii\web\View 来管理和渲染这个视图文件。
除了 $this之外,上述示例中的视图有其他预定义变量如 $model, 这些变量代表从控制器或其他触发视图渲染的对象 传入 到视图的数据。
技巧: 将预定义变量列到视图文件头部注释处,这样可被IDE编辑器识别,也是生成视图文档的好方法。
安全
当创建生成HTML页面的视图时,在显示之前将用户输入数据进行转码和过滤非常重要, 否则,你的应用可能会被跨站脚本 攻击。
要显示纯文本,先调用 yii\helpers\Html::encode() 进行转码,例如如下代码将用户名在显示前先转码:
<?php use yii\helpers\Html; ?> <div class="username"> <?= Html::encode($user->name) ?> </div>
要显示HTML内容,先调用 yii\helpers\HtmlPurifier 过滤内容,例如如下代码将提交内容在显示前先过滤:
<?php use yii\helpers\HtmlPurifier; ?> <div class="post"> <?= HtmlPurifier::process($post->text) ?> </div>
技巧: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 = [])
控制器中渲染
在 控制器 中,可调用以下控制器方法来渲染视图:
- 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, ]); } }
小物件
小物件是 CWidget 或其子类的实例.它是一个主要用于表现数据的组件.小物件通常内嵌于一个视图来产生一些复杂而独立的用户界面.例如,一个日历小物件可用于渲染一个复杂的日历界面.小物件使用户界面更加可复用.
我们可以按如下视图脚本来使用一个小物件:
<?php $this->beginWidget('path.to.WidgetClass'); ?> ...可能会由小物件获取的内容主体... <?php $this->endWidget(); ?>
或者
<?php $this->widget('path.to.WidgetClass'); ?>
后者用于不需要任何 body 内容的组件.
小物件可通过配置来定制它的表现.这是通过调用 CBaseController::beginWidget 或 CBaseController::widget 设置其初始化属性值来完成的.例如,当使用 CMaskedTextField 小物件时,我们想指定被使用的 mask (可理解为一种输出格式,译者注).我们通过传递一个携带这些属性初始化值的数组来实现.这里的数组的键是属性的名称,而数组的值则是小物件属性所对应的值.正如以下所示 :
<?php $this->widget('CMaskedTextField',array( 'mask'=>'99/99/9999' )); ?>
继承 CWidget 并覆盖其init() 和 run() 方法,可以定义一个新的小物件:
class MyWidget extends CWidget { public function init() { // 此方法会被 CController::beginWidget() 调用 } public function run() { // 此方法会被 CController::endWidget() 调用 } }
小物件可以像一个控制器一样拥有它自己的视图.默认情况下,小物件的视图文件位于包含了小物件类文件目录的 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 组件:
<?= $this->render('_overview') ?>
其他地方渲染
在任何地方都可以通过表达式 Yii::$app->view 访问 yii\base\View 应用组件, 调用它的如前所述的方法渲染视图,例如:
// 显示视图文件 "@app/views/site/license.php" echo \Yii::$app->view->renderFile('@app/views/site/license.php');
您可能感兴趣的文章:
- 详解PHP的Yii框架中自带的前端资源包的使用
- 简介PHP的Yii框架中缓存的一些高级用法
- 深入解析PHP的Yii框架中的缓存功能
- PHP的Yii框架中View视图的使用进阶
- PHP的Yii框架中Model模型的学习教程
- 详解PHP的Yii框架中的Controller控制器
- PHP的Yii框架中移除组件所绑定的行为的方法
- PHP的Yii框架中行为的定义与绑定方法讲解
- 深入讲解PHP的Yii框架中的属性(Property)
- 详解PHP的Yii框架中扩展的安装与使用

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
