


Detailed explanation of the methods of creating views and rendering views in PHP's Yii framework, yii framework_PHP tutorial
Jul 12, 2016 am 08:55 AMDetailed 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.
<?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 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:
<?php use yii\helpers\Html; ?> <div class="username"> <?= Html::encode($user->name) ?> </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:
<?php use yii\helpers\HtmlPurifier; ?> <div class="post"> <?= HtmlPurifier::process($post->text) ?> </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 傳遞給視圖的數(shù)據(jù) * @return string 渲染結(jié)果 */ 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:
<?php $this->beginWidget('path.to.WidgetClass'); ?> ...可能會由小物件獲取的內(nèi)容主體... <?php $this->endWidget(); ?>
or
<?php $this->widget('path.to.WidgetClass'); ?>
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:
<?php $this->widget('CMaskedTextField',array( 'mask'=>'99/99/9999' )); ?>
Inherit CWidget and override its init() and run() methods to define a new widget:
class MyWidget extends CWidget { public function init() { // 此方法會被 CController::beginWidget() 調(diào)用 } public function run() { // 此方法會被 CController::endWidget() 調(diào)用 } }
小物件可以像一個控制器一樣擁有它自己的視圖.默認(rèn)情況下,小物件的視圖文件位于包含了小物件類文件目錄的 views 子目錄之下.這些視圖可以通過調(diào)用 CWidget::render() 渲染,這一點和控制器很相似.唯一不同的是,小物件的視圖沒有布局文件支持。另外,小物件視圖中的$this指向小物件實例而不是控制器實例。
視圖中渲染
可以在視圖中渲染另一個視圖,可以調(diào)用yii\base\View視圖組件提供的以下方法:
- yii\base\View::render(): 渲染一個 視圖名.
- yii\web\View::renderAjax(): 渲染一個 視圖名 并注入所有注冊的JS/CSS腳本和文件,通常使用在響應(yīng)AJAX網(wǎng)頁請求的情況下。
- yii\base\View::renderFile(): 渲染一個視圖文件目錄或別名下的視圖文件。
例如,視圖中的如下代碼會渲染該視圖所在目錄下的 _overview.php 視圖文件, 記住視圖中 $this 對應(yīng) yii\base\View 組件:
<?= $this->render('_overview') ?>
其他地方渲染
在任何地方都可以通過表達(dá)式 Yii::$app->view 訪問 yii\base\View 應(yīng)用組件, 調(diào)用它的如前所述的方法渲染視圖,例如:
// 顯示視圖文件 "@app/views/site/license.php" echo \Yii::$app->view->renderFile('@app/views/site/license.php');
您可能感興趣的文章:
- 詳解PHP的Yii框架中自帶的前端資源包的使用
- 簡介PHP的Yii框架中緩存的一些高級用法
- 深入解析PHP的Yii框架中的緩存功能
- PHP的Yii框架中View視圖的使用進(jìn)階
- PHP的Yii框架中Model模型的學(xué)習(xí)教程
- 詳解PHP的Yii框架中的Controller控制器
- PHP的Yii框架中移除組件所綁定的行為的方法
- PHP的Yii框架中行為的定義與綁定方法講解
- 深入講解PHP的Yii框架中的屬性(Property)
- 詳解PHP的Yii框架中擴展的安裝與使用

Hot AI Tools

Undress AI Tool
Undress images for free

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

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

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

PHPhasthreecommentstyles://,#forsingle-lineand/.../formulti-line.Usecommentstoexplainwhycodeexists,notwhatitdoes.MarkTODO/FIXMEitemsanddisablecodetemporarilyduringdebugging.Avoidover-commentingsimplelogic.Writeconcise,grammaticallycorrectcommentsandu

PHPisaserver-sidescriptinglanguageusedforwebdevelopment,especiallyfordynamicwebsitesandCMSplatformslikeWordPress.Itrunsontheserver,processesdata,interactswithdatabases,andsendsHTMLtobrowsers.Commonusesincludeuserauthentication,e-commerceplatforms,for

How to start writing your first PHP script? First, set up the local development environment, install XAMPP/MAMP/LAMP, and use a text editor to understand the server's running principle. Secondly, create a file called hello.php, enter the basic code and run the test. Third, learn to use PHP and HTML to achieve dynamic content output. Finally, pay attention to common errors such as missing semicolons, citation issues, and file extension errors, and enable error reports for debugging.

The key steps to install PHP on Windows include: 1. Download the appropriate PHP version and decompress it. It is recommended to use ThreadSafe version with Apache or NonThreadSafe version with Nginx; 2. Configure the php.ini file and rename php.ini-development or php.ini-production to php.ini; 3. Add the PHP path to the system environment variable Path for command line use; 4. Test whether PHP is installed successfully, execute php-v through the command line and run the built-in server to test the parsing capabilities; 5. If you use Apache, you need to configure P in httpd.conf

TohandlefileoperationsinPHP,useappropriatefunctionsandmodes.1.Toreadafile,usefile_get_contents()forsmallfilesorfgets()inaloopforline-by-lineprocessing.2.Towritetoafile,usefile_put_contents()forsimplewritesorappendingwiththeFILE_APPENDflag,orfwrite()w

The basic syntax of PHP includes four key points: 1. The PHP tag must be ended, and the use of complete tags is recommended; 2. Echo and print are commonly used for output content, among which echo supports multiple parameters and is more efficient; 3. The annotation methods include //, # and //, to improve code readability; 4. Each statement must end with a semicolon, and spaces and line breaks do not affect execution but affect readability. Mastering these basic rules can help write clear and stable PHP code.

The steps to install PHP8 on Ubuntu are: 1. Update the software package list; 2. Install PHP8 and basic components; 3. Check the version to confirm that the installation is successful; 4. Install additional modules as needed. Windows users can download and decompress the ZIP package, then modify the configuration file, enable extensions, and add the path to environment variables. macOS users recommend using Homebrew to install, and perform steps such as adding tap, installing PHP8, setting the default version and verifying the version. Although the installation methods are different under different systems, the process is clear, so you can choose the right method according to the purpose.

The key to writing Python's ifelse statements is to understand the logical structure and details. 1. The infrastructure is to execute a piece of code if conditions are established, otherwise the else part is executed, else is optional; 2. Multi-condition judgment is implemented with elif, and it is executed sequentially and stopped once it is met; 3. Nested if is used for further subdivision judgment, it is recommended not to exceed two layers; 4. A ternary expression can be used to replace simple ifelse in a simple scenario. Only by paying attention to indentation, conditional order and logical integrity can we write clear and stable judgment codes.
