Advanced View usage in the Yii Framework of PHP. yiiview_PHP tutorial

Source: Internet
Author: User
In the Yii Framework of PHP, yiiview is advanced in View usage. In the Yii Framework of PHP, the usage of the View is advanced. when the yiiview View name is used to render the View, you can specify a View name or View file path alias, in most cases, the former is used because the former is simplified in the Yii Framework of PHP.

View Name

When rendering a view, you can specify a View name or view file path/alias. In most cases, the former is used because it is concise and flexible. we call the view with the name as the View name.

View names can be directed to the corresponding view file path based on the following rules:

The View name can omit the file extension. in this case,. php is used as an extension. The View Name about corresponds to the about. php file name;
The View name starts with a double slash //. the corresponding view file path is @ app/views/ViewName, which means that the view file is located in the yii \ base \ Application: viewPath path, for example, // site/about corresponds to @ app/views/site/about. php.
The View name starts with a single slash (/). The View file path starts with the yii \ base \ Module: viewPath of the currently used Module. If no Module exists, start with @ app/views/ViewName, for example, if the current module is user,/user/create corresponds to @ app/modules/user/views/user/create. php. if it is not in the module,/user/create corresponds to @ app/views/user/create. php.
If yii \ base \ View: context renders the View and the context implements yii \ base \ ViewContextInterface, the View file path starts from the context's yii \ base \ ViewContextInterface: getViewPath, this is mainly used to render views in controllers and widgets. for example, if the context is controller SiteController, site/about corresponds to @ app/views/site/about. php.
If the view renders another view, the directory containing another view file starts with the file path of the current view, for example, @ app/views/post/index. the items rendered by php correspond to @ app/views/post/item.
According to the above rules, in the controller, app \ controllers \ PostController calls $ this-> render ('View') and actually renders @ app/views/post/view. php view file. when $ this-> render ('_ Overview') is called in this view file, @ app/views/post/_ overview will be rendered. php view file.

Access data in the view

There are two ways to access data in the view: push and pull.

The push method is to pass data through the second parameter of the view rendering method. the data format should be an array of name-value. during view rendering, PHP extract () is called () method to convert the array to a variable accessible to the view. For example, the rendering View code of the following controller pushes two variables to the report View: $ foo = 1 and $ bar = 2.

echo $this->render('report', [  'foo' => 1,  'bar' => 2,]);

The pull mode allows the View to actively obtain data (such as yii: $ app) from the Yii \ base \ View component or other objects ), use the following expression $ this-> context in the view to obtain the controller ID. you can obtain any attributes or methods of the controller in the report view, as shown in the following code.

The controller ID is: <?= $this->context->id ?>?>

The push mode makes the view less dependent on the context object, which is the preferred way to obtain data from the view. The disadvantage is that you need to manually build an array, which is cumbersome and prone to errors during rendering in different places.

Share data between views

The yii \ base \ View component provides the yii \ base \ View: params parameter attribute to allow different views to share data.

For example, in the about view, you can use the following code to specify the current part of the current breadcrumbs.

$this->params['breadcrumbs'][] = 'About Us';

In the layout file (also a View), you can use the values added to the yii \ base \ View: params array in sequence to generate the breadcrumbs:

<?= yii\widgets\Breadcrumbs::widget([  'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],]) ?>

Layout

A layout is a special view that represents the public part of multiple views. for example, most Web applications share the same page header and footer, repeat the same page header and footer in each view. a better way is to put these headers in a layout, render the content view, and embed them into the layout in a proper place.

Create layout

Because the layout is also a view, it can be created like a normal view. the layout is stored in the @ app/views/layouts path by default. the layout used in the Module should be stored in yii \ base \ Module:: in the views/layouts path under the basePath Module directory, you can configure yii \ base \ Module: layoutPath to customize the default layout path of an application or Module.

The following example shows a general layout. Note that as an example, much code is simplified. In practice, you may want to add more content, such as header labels and main menus.

<? Phpuse yii \ helpers \ Html;/* @ var $ this yii \ web \ View * // * @ var $ content string */?> <? Php $ this-> beginPage ()?>  
 <? = Html: csrf0000ags ()?><? = Html: encode ($ this-> title)?><? Php $ this-> head ()?><? Php $ this-> beginBody ()?>
 
  
My Company
 <? = $ Content?>
 
  
©2014 by My Company
 <? Php $ this-> endBody ()?><? Php $ this-> endPage ()?>

As shown above, the layout generates HTML tags for each page.In the label, print the $ content variable. The $ content variable indicates that the rendering result is passed to the layout content view when the yii \ base \ Controller: render () Controller rendering method is called.

Most views should call the following methods in the above code to trigger events about the rendering process, so that scripts and labels registered elsewhere will be added to the places where these methods are called.

  • Yii \ base \ View: beginPage (): This method should be called at the beginning of the layout. it triggers the yii \ base \ View: EVENT_BEGIN_PAGE event indicating the start of the page.
  • Yii \ base \ View: endPage (): This method should be called at the end of the layout. it triggers the yii \ base \ View: EVENT_END_PAGE time at the end of the page.
  • Yii \ web \ View: head (): This method should be inTag, which generates a placeholder. when the page rendering ends, the registered header HTML code (such as the link tag and meta tag) is replaced.
  • Yii \ web \ View: beginBody (): This method should be inThe tag is called at the beginning. it triggers the yii \ web \ View: EVENT_BEGIN_BODY event and generates a placeholder. the registered HTML code (such as JavaScript) is replaced at the beginning of the page body.
  • Yii \ web \ View: endBody (): This method should be inThe end of the tag is called. it triggers the yii \ web \ View: EVENT_END_BODY event and generates a placeholder. the registered HTML code (such as JavaScript) is replaced at the end of the page body.

Access data in layout

In the layout, you can access two predefined variables: $ this and $ content. The former corresponds to the yii \ base \ View component similar to the common View, and the latter includes calling yii \ base \ Controller :: the render () method renders the results of the content view.

To access other data in the layout, you must use the pull method described in the access data section in the view. if you want to transfer data from the content view to the layout, you can use the method in the share data section between views.

Use layout

For example, if the Controller calls the yii \ base \ Controller: render () method to render the view, the layout is used to render the view, @ app/views/layouts/main is used by default. php layout file.

You can configure yii \ base \ Application: layout or yii \ base \ Controller: layout to use other layout files. The former manages the layout of all controllers, the latter overwrites the former to control the layout of a single controller. For example, the following code enables the post Controller to use @ app/views/layouts/post when rendering a view. php is used as the layout file. if the layout attribute is not changed, the controller uses @ app/views/layouts/main by default. php is used as the layout file.

namespace app\controllers;use yii\web\Controller;class PostController extends Controller{  public $layout = 'post';  // ...}

For controllers in the Module, you can configure the yii \ base \ Module: layout attribute of the Module to specify that the layout file is applied to all controllers of the Module.

Because layout can be configured at different levels (controller, module, and application), Yii uses two steps behind the scenes to determine the actual layout of the controller.

Step 1: It determines the layout value and context module:

If the yii \ base \ Controller: layout attribute of the Controller is not null, use it as the layout value. The yii \ base \ Controller: module of the Controller serves as the context module.
If yii \ base \ Controller: layout is empty, find the first yii \ base \ Module: layout Module from the Controller's ancestor Module (including applications, use this Module as the context Module, and use its yii \ base \ Module: layout value as the layout value. if none of them are found, the layout is not used.
Step 2: it determines that the layout value in step 1 corresponds to the actual layout file of the context module. the layout value can be:

Path alias (for example, @ app/views/layouts/main ).
Absolute path (such as/main): the layout value starts with a slash. in the Application's [[yii \ base \ Application :: layoutPath | layout path] Searches for the actual layout file in the layout path. the default layout path is @ app/views/layouts.
Relative path (such as main): In the context Module's yii \ base \ Module: layoutPath layout path, find the actual layout file. the default layout path is yii \ base \ Module :: the views/layouts directory under the basePath module directory.
Boolean value false: no layout is used.
The layout value does not contain the file extension. by default,. php is used as the extension.

Nested layout

Sometimes you want to nest one layout to another. for example, you want to use different la s in different places on the Web site. at the same time, these la s share the same basic layout to generate a global HTML5 page structure, you can call the yii \ base \ View: beginContent () and yii \ base \ View: endContent () methods in the sub-layout, as shown below:

<?php $this->beginContent('@app/views/layouts/base.php'); ?>...child layout content here...<?php $this->endContent(); ?>

As shown above, the sub-layout content should be transmitted between the yii \ base \ View: beginContent () and yii \ base \ View: endContent () methods to yii \ base \ View :: the beginContent () parameter specifies the parent layout. the parent layout can be a layout file or alias.

Multiple layers of nested layout can be used in the preceding method.

Use data blocks

A data block can be used together with the layout to specify that the view content is displayed in another place. for example, you can define a data block in the content view to display it in the layout.

Call yii \ base \ View: beginBlock () and yii \ base \ View: endBlock () to define the data block, use $ view-> blocks [$ blockID] to access the data block. $ blockID is the unique ID specified when the data block is defined.

The following example shows how to use data blocks in the content view for layout.

First, define one or more data blocks in the content view:

...<?php $this->beginBlock('block1'); ?>...content of block1...<?php $this->endBlock(); ?>...<?php $this->beginBlock('block3'); ?>...content of block3...<?php $this->endBlock(); ?>

In the Layout view, data blocks are rendered if they are available. if the data is not defined, some default content is displayed.

...<?php if (isset($this->blocks['block1'])): ?>  <?= $this->blocks['block1'] ?><?php else: ?>  ... default content for block1 ...<?php endif; ?>...<?php if (isset($this->blocks['block2'])): ?>  <?= $this->blocks['block2'] ?><?php else: ?>  ... default content for block2 ...<?php endif; ?>...<?php if (isset($this->blocks['block3'])): ?>  <?= $this->blocks['block3'] ?><?php else: ?>  ... default content for block3 ...<?php endif; ?>...

Use View components

The yii \ base \ View component provides many view-related features. you can create a yii \ base \ View or its subclass instance to obtain the View component. In most cases, the view application component is used, you can configure this component in application configuration as follows:

[  // ...  'components' => [    'view' => [      'class' => 'app\components\View',    ],    // ...  ],]

The view component provides the following practical view-related features. each item is described in an independent section:

  • Topic: allows you to develop and modify themes for your website;
  • Fragment cache: Allows you to cache fragment on a Web page;
  • Customer script processing: supports registration and rendering of CSS and JavaScript;
  • Resource package processing: supports resource package registration and rendering;
  • Template engine: Allows you to use other template engines, such as Twig and Smarty.

When developing Web pages, you may also frequently use the following small practical features.

Set page title

Each Web page should have a title. under normal circumstances, the title label is displayed in the layout, but in fact the title is mostly determined by the content view rather than the layout. to solve this problem, yii \ web \ View provides the yii \ web \ View: title attribute to transfer the title information from the content View to the layout.

To use this feature, set the page title in each content view as follows:

<? Php $ this-> title = 'My page title';?> In the view, make sure thatThe section contains the following code:<? = Html: encode ($ this-> title)?>

Register Meta tags

Web pages usually need to generate various meta tags for different browsers, suchThe page title, which is usually generated in the layout.

To generate a meta tag in the content View, you can call the yii \ web \ View: register1_ag () method in the content View, as shown below:

<?php$this->registerMetaTag(['name' => 'keywords', 'content' => 'yii, framework, php']);?>

The above code registers a "keywords" meta tag in the view component, rendering the registered meta tag after layout rendering, and then, the following HTML code is inserted into the layout to call the yii \ web \ View: head () method:

 

Note: If you call the yii \ web \ View: register1_ag () method multiple times, it will register multiple meta tags and will not check whether duplicate tags are detected during registration.

To ensure that there is only one element tag, you can specify the key as the second parameter when calling the method. for example, the following code registers the "description" element tag twice, but only renders the second one.

$this->registerMetaTag(['name' => 'description', 'content' => 'This is my cool website made with Yii!'], 'description');$this->registerMetaTag(['name' => 'description', 'content' => 'This website is about funny raccoons.'], 'description');

Register a link tag

Similar to Meta tags, link tags are sometimes useful, such as customizing website icons, specifying Rss subscriptions, or authorizing OpenIDs to other servers. You can call yii \ web \ View: registerLinkTag () in a similar way as a metadata tag. for example, register a link tag in the content View as follows:

$this->registerLinkTag([  'title' => 'Live News for Yii',  'rel' => 'alternate',  'type' => 'application/rss+xml',  'href' => 'http://www.yiiframework.com/rss.xml/',]);

The above code is converted

The code is as follows:


Similar to yii \ web \ View: registerMetaTag (), call the yii \ web \ View: registerLinkTag () key to avoid duplicate link tags.

View events

The yii \ base \ View component will trigger several events during the View rendering process. before sending events to end users, it can respond to these events to add content to the View or adjust the rendering result.

  • Yii \ base \ View: EVENT_BEFORE_RENDER: triggered when the controller rendering file starts. you can set yii \ base \ ViewEvent: isValid to false to cancel View rendering.
  • Yii \ base \ View: EVENT_AFTER_RENDER: triggered when yii \ base \ View: beginPage () is called in the layout. you can obtain yii \ base \ ViewEvent :: the rendering result of the output. you can modify this attribute to modify the rendering result.
  • Yii \ base \ View: EVENT_BEGIN_PAGE: triggered when layout calls yii \ base \ View: beginPage;
  • Yii \ base \ View: EVENT_END_PAGE: call yii \ base \ View: endPage () in layout;
  • Yii \ web \ View: EVENT_BEGIN_BODY: triggered when layout calls yii \ web \ View: beginBody;
  • Yii \ web \ View: EVENT_END_BODY: triggered when layout calls yii \ web \ View: endBody.

For example, the following code adds the current date to the end of the page:

\Yii::$app->view->on(View::EVENT_END_BODY, function () {  echo date('Y-m-d');});

Rendering static pages

A static page refers to a Web page whose content is static and does not require a controller to transmit dynamic data.

You can place HTML code in the view and use the following code in the controller to output a static page:

public function actionAbout(){  return $this->render('about');}

If a Web site contains many static pages, repeated similar code may be cumbersome. to solve this problem, you can use an independent operation called yii \ web \ ViewAction in the controller. For example:

namespace app\controllers;use yii\web\Controller;class SiteController extends Controller{  public function actions()  {    return [      'page' => [        'class' => 'yii\web\ViewAction',      ],    ];  }}

Now, if you create a view named about under the @ app/views/site/pages directory, you can use the following rul to display the view:

Http: // localhost/index. php? R = site/page & view = about
In GET, The view parameter informs yii \ web \ ViewAction of The view requested by the operation, and searches for the view in the @ app/views/site/pages directory. you can configure yii \ web \ ViewAction:: viewPrefix: modify the Directory of the search View.

Best practices

The view is responsible for displaying the data of the model in the format you want. In short, the view

  • Display code, such as HTML, and simple PHP code should be included to control, format, and render data;
  • The code for executing data query should not be included. this code should be placed in the model;
  • Direct access to request data, such as $ _ GET and $ _ POST, should be avoided. such requests should be executed in the controller. if data needs to be requested, the controller should push the requests to the view.
  • Model attributes can be read but cannot be modified.
  • To make the model easier to maintain and avoid creating views that are too complex or contain too much redundant code, follow these steps:
  • Use the layout to display public code (such as the header and tail of the page );
  • Divide a complex view into several small Views. you can use the rendering method described above to render these small Views and assemble them into large views;
  • Create and use widgets as View data blocks;
  • Create and use the helper class to convert and format data in the view.
Articles you may be interested in:
  • Describes how to use the frontend resource package in the Yii Framework of PHP.
  • Introduction to some advanced usage of cache in PHP Yii Framework
  • In-depth analysis of the cache function in the PHP Yii Framework
  • Detailed description of how to create and render views in the Yii Framework of PHP
  • PHP Yii Framework Model learning tutorial
  • Detailed explanation of Controller in PHP Yii Framework
  • How to remove the behavior bound to a component from the Yii Framework of PHP
  • Definition and binding of behavior in PHP Yii Framework
  • In-depth explanation of attributes in PHP Yii Framework)
  • Detailed description of PHP Yii Framework extension installation and use

When rendering a view, you can specify a View name or view file path/alias. In most cases, the former is used because the former is simple...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.