


Detailed explanation of the methods of creating views and rendering views in PHP's Yii framework
Views are part of the MVC pattern. It is the code that displays data to end users. In web applications, views are created based on view templates. The view template is a PHP script file, which mainly contains HTML code and display PHP code, and is managed through the yii\web\View application component. This component mainly provides general methods to help view construction and rendering. For simplicity, we call the view template or view template file a view.
Create View
As mentioned before, the view is a PHP script containing HTML and PHP code. The following code is a view of a login form. You can see that the PHP code is used to generate dynamic content, such as Page title and form, HTML code organizes it into a beautiful HTML page.
<?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><?= 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(); ?>
In the view, you can access $this to point to yii\web\View to manage and render this view file.
In addition to $this, the view in the above example has other predefined variables such as $model. These variables represent data passed to the view from the controller or other objects that trigger the rendering of the view.
Tips: List the predefined variables in the header comment of the view file so that they can be recognized by the IDE editor. It is also a good way to generate view documents.
Security
When creating views that generate HTML pages, it is important to transcode and filter user input data before displaying it, otherwise, your application may be vulnerable to cross-site scripting attacks.
To display plain text, first call yii\helpers\Html::encode() for transcoding. For example, the following code transcodes the user name before displaying it:
<?php use yii\helpers\Html; ?> <div class="username"> <?= Html::encode($user->name) ?> </div>
To display HTML Content, first call yii\helpers\HtmlPurifier to filter the content. For example, the following code will filter the submitted content before displaying it:
<?php use yii\helpers\HtmlPurifier; ?> <div class="post"> <?= HtmlPurifier::process($post->text) ?> </div>
Tips: HTMLPurifier does a good job of ensuring the security of the output data, but its performance is not good. If your application requires high performance, consider caching the filtered results.
Organization View
Similar to controllers and models, there are some conventions on organizing views:
The view files rendered by the controller are placed by default at @app/views/ControllerID directory, where ControllerID corresponds to the controller ID. For example, the controller class is PostController, the view file directory should be @app/views/post, and the directory corresponding to the controller class PostCommentController is @app/views/post-comment. If it is in a module controller, the directory should be the views/ControllerID directory under the yii\base\Module::basePath module directory;
The view files for widget rendering are placed in the WidgetPath/views directory by default, where WidgetPath represents the location of the widget class file directory;
For view files rendered by other objects, it is recommended to follow similar rules to widgets.
You can override the yii\base\ViewContextInterface::getViewPath() method of the controller or widget to customize the default directory of view files.
Render view
The render view method can be called in the controller, widget, or elsewhere to render the view. The method is similar to the following format:
/** * @param string $view 视图名或文件路径,由实际的渲染方法决定 * @param array $params 传递给视图的数据 * @return string 渲染结果 */ methodName($view, $params = [])
Rendering in the controller
In the controller, you can call the following controller methods to render the view:
yii\base\Controller::render(): Render a view name and use a layout to return the rendering result .
yii\base\Controller::renderPartial(): Renders a view name and does not use layout.
yii\web\Controller::renderAjax(): Renders a view name without using layout, and injects all registered JS/CSS scripts and files, usually used in response to AJAX web page requests.
yii\base\Controller::renderFile(): Render a view file in a view file directory or alias.
For example:
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, ]); } }
Widget
A widget is an instance of CWidget or its subclass. It is a component mainly used to represent data. Widgets are usually embedded in a view To generate some complex and independent user interfaces. For example, a calendar widget can be used to render a complex calendar interface. Widgets make the user interface more reusable.
We can use a view script as follows Widgets:
<?php $this->beginWidget('path.to.WidgetClass'); ?> ...可能会由小物件获取的内容主体... <?php $this->endWidget(); ?>
or
<?php $this->widget('path.to.WidgetClass'); ?>
The latter is used for components that do not require any body content.
Widgets can be configured to customize their performance. This is done through This is done by calling CBaseController::beginWidget or CBaseController::widget to set its initialization property value. For example, when using the CMaskedTextField widget, we want to specify the mask to be used (can be understood as an output format, translator's note). We This is achieved by passing an array carrying the initialization values of these properties. The key of the array here is the name of the property, and the value of the array is the value corresponding to the widget property. As shown below:
<?php $this->widget('CMaskedTextField',array( 'mask'=>'99/99/9999' )); ?>
Inheritance CWidget and override its init() and run() methods, you can define a new widget:
class MyWidget extends CWidget { public function init() { // 此方法会被 CController::beginWidget() 调用 } public function run() { // 此方法会被 CController::endWidget() 调用 } }
The widget can have its own view like a controller. By default, the widget's view The file is located under the views subdirectory of the directory that contains the widget class files. These views can be rendered by calling CWidget::render(), which is very similar to the controller. The only difference is that the widget's view does not have layout file support . In addition, $this in the widget view points to the widget instance rather than the controller instance.
Rendering in a view
You can render another view in a view by calling the following method provided by the yii\base\View view component:
yii\base\View: :render(): Render a view name.
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中文网!

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python are both high-level programming languages that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

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.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools