search
HomeBackend DevelopmentPHP TutorialDetailed explanation of the methods of creating views and rendering views in PHP's Yii framework, yii framework_PHP tutorial

Detailed explanation of the methods of creating views and rendering views in PHP's Yii framework. The 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. It is managed through the yiiwebView application component, which mainly provides Generic methods help view construction and rendering. For simplicity, we call the view template or view template file a view.

Create View

As mentioned earlier, 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 titles and forms, and the HTML code organizes it into A beautiful HTML page.

<&#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;>

In the view, you can access $this to point to yiiwebView to manage and render this view file.

In addition to $this, the view in the above example has other predefined variables such as $model, which represent data passed to the view from the controller or other objects that trigger the rendering of the view.

Tip: 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.
Safety

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 yiihelpersHtml::encode() for transcoding. For example, the following code transcodes the username before displaying it:

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

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

To display HTML content, first call yiihelpersHtmlPurifier to filter the content. For example, the following code will filter the submitted content before displaying it:

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

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

Tips: HTMLPurifier does a good job of ensuring the security of 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 for organizing views:

The view files rendered by the controller are placed in the @app/views/ControllerID directory by default, where ControllerID corresponds to the controller ID. For example, the controller class is PostController, and the view file directory should be @app/views/post, and the controller class The directory corresponding to PostCommentController is @app/views/post-comment. If it is a controller in a module, the directory should be the views/ControllerID directory under the yiibaseModule::basePath module directory;
View files rendered by widgets are placed in the WidgetPath/views directory by default, where WidgetPath represents the directory where the widget class files are located;
For view files rendered by other objects, it is recommended to follow similar rules as for widgets.
You can override the yiibaseViewContextInterface::getViewPath() method of a controller or widget to customize the default directory for view files.

Render view

The render view method can be called in a 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 a controller, the following controller methods can be called to render the view:

  • yiibaseController::render(): Render a view name and use a layout to return the rendering result.
  • yiibaseController::renderPartial(): Renders a view name and does not use layout.
  • yiiwebController::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.
  • yiibaseController::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,
    ]);
  }
}

Small items
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 produce some complex and independent user interfaces. For example, a calendar widget can be used Used to render a complex calendar interface. Small objects make the user interface more reusable.

We can use a widget according to the following view script:

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

or

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

The latter is used for components that do not require any body content.

The widget can be configured to customize its performance. 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 that it is used mask (can be understood as an output format, translator's note). We do this 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 attribute of the small object. The corresponding value. As shown below:

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

Inherit CWidget and override its init() and run() methods to define a new widget:

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 组件:

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

其他地方渲染

在任何地方都可以通过表达式 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框架中扩展的安装与使用

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/1117072.htmlTechArticlePHP的Yii框架中创建视图和渲染视图的方法详解,yii框架 视图是 MVC 模式中的一部分。 它是展示数据到终端用户的代码,在网页应用中,根据...
Statement
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
PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

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 and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

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.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

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 and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

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.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

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

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

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.

How does PHP handle object cloning (clone keyword) and the __clone magic method?How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AM

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP vs. Python: Use Cases and ApplicationsPHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor