yiiview_php tutorial for using Advanced view view in the Yii framework of PHP

Source: Internet
Author: User

The use of view view in the PHP yii framework is advanced, Yiiview


View Name

When rendering a view, you can specify a view name or view file path/alias, in most cases using the former because it is simple and flexible, we call the name view the view name.

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

The view name omits the file name extension, in which case the. PHP is used as an extension, and the view name is about the about.php file name;
The view name begins with a double slash///and the corresponding view file path is @app/views/viewname, which means that the view file is found under the Yii\base\application::viewpath path, for example//site/about to @app/ views/site/about.php.
The view name begins with a single slash/start, and the view file path begins with the Yii\base\module::viewpath of the current module, and 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 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 is yii\base\viewcontextinterface by the context: Beginning with Getviewpath (), this is primarily used for rendering views in controllers and widgets, such as if the context is for a controller sitecontroller,site/about corresponding to the @app/views/site/about.php.
If the view renders another view, the directory containing the other view file begins with the file path of the current view, for example, the item rendered by the view @app/views/post/index.php corresponds to the @app/views/post/item.
According to the above rules, App\controllers\postcontroller calls $this->render (' View ') in the controller, actually renders the @app/views/post/view.php view file, When you call $this->render (' _overview ') in the view file, the @app/views/post/_overview.php view file is rendered.

Accessing data in a view

There are two ways to access data in a view: Push and pull.

The push method is to pass the data through the second parameter of the view rendering method, the data format should be a name-value array, and when the view renders, call the PHP extract () method to convert the array to a variable that the view can access. For example, the rendering view code for the following controller pushes 2 variables into the report view: $foo = 1 and $bar = 2.

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

The pull mode allows the view to proactively obtain data from Yii\base\view view components or other objects (such as Yii:: $app), using the following expression in the view $this->context to get to the controller ID, Allows you to get any properties or methods of the controller in the report view, such as the following code to get the controller ID.

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

The push way makes the view less dependent on the context object, is the view gets the data first use, the disadvantage is the need to build the array manually, some cumbersome, in different places rendering error prone.

Sharing data between views

The Yii\base\view View component provides Yii\base\view::p arams parameter properties 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 a layout file (also a view), you can use the values of the Yii\base\view::p arams array to generate the display breadcrumbs:

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

Layout

A layout is a special view that represents the public parts of multiple views, for example, most web apps share the same header and footer, repeating the same header and footer in each view, and a better way to put these public in a layout, and then embed the content view in the layout where appropriate.

Creating layouts

Because the layout is also a view, it can be created as a normal view, the layout is stored under the @app/views/layouts path by default, and the layout used in the module should be stored under the views/layouts path in the Yii\base\module::basepath module directory. Configurable Yii\base\module::layoutpath to customize the layout default path of an app or module.

The following example is a layout of the general content, note as an example, simplifies a lot of code, in practice, you may want to add more content, such as head tags, main menu and so on.

<?phpuse yii\helpers\html;/* @var $this yii\web\view *//* @var $content string string */?><?php $this->beginpage ()?>  
 
    <?= html::csrfmetatags ()?>  <?= Html::encode ($this->title)?>  <?php $this->head ()? ><?php $this->beginbody ()?>  
 
  
   
 My
  company  <?= $ Content?>  
 
  
   
 ©
  <?php $this->endbody () ><?php $this EndPage ()?>

As shown above, the layout generates a common HTML tag for each page, in the label, the $content variable is printed, and the $content variable represents the rendered result of the content view that is passed to the layout when the Yii\base\controller::render () controller renders the method call.

Most views should call the following methods in the preceding code, which trigger events about the rendering process so that scripts and tags registered elsewhere are added to these method calls.

    • Yii\base\view::beginpage (): The method should be called at the beginning of the layout, which triggers the Yii\base\view::event_begin_page event that indicates the start of the page.
    • Yii\base\view::endpage (): The method should be called at the end of the layout, which triggers the yii\base\view::event_end_page time indicating the end of the page.
    • Yii\web\view::head (): The method should be called in the label of the HTML page, which generates a placeholder that will be replaced by the registered header HTML code (e.g., link tag, meta tag) at the end of page rendering.
    • Yii\web\view::beginbody (): The method should be called at the beginning of the label, which triggers the Yii\web\view::event_begin_body event and generates a placeholder, The HTML code (such as JavaScript) that is registered is replaced at the beginning of the page body.
    • Yii\web\view::endbody (): The method should be called at the end of the label, which triggers the Yii\web\view::event_end_body event and generates a placeholder. The HTML code (such as JavaScript) that is registered is replaced at the end of the page body.

Accessing data in a layout

Two predefined variables are accessible in the layout: The Yii\base\view view component that corresponds to the normal view and the $content, which contains the result of calling the Yii\base\controller::render () method to render the content view.

If you want to access other data in the layout, you must use the Pull method described in the Access Data section of the view, and if you want to pass data from the content view to the layout, use the methods in the Share data section of the view.

Working with layouts

As described in the rendering section of the controller, when the controller invokes the Yii\base\controller::render () method to render the view, the layout is used in the render result, and the @app/views/layouts/main.php layout file is used by default.

You can configure Yii\base\application::layout or yii\base\controller::layout to use other layout files that manage the layout of all controllers, which override the former to control the layout of a single controller. For example, the following code uses the @app/views/layouts/post.php as the layout file when the post controller renders the view, and if the layout property does not change, the controller uses @app/views/layouts/main.php as the layout file by default.

Namespace App\controllers;use yii\web\controller;class Postcontroller extends controller{public  $layout = ' post ';  // ...}

For a controller in a module, the Yii\base\module::layout property of the configurable module specifies that the layout file is applied to all the controllers of the module.

Since layout can be configured at different levels (Controller, module, application), it uses two steps in the behind-the-scenes yii to determine the actual layout used by the controller.

In the first step, it determines the value of the layout and the context module:

If the controller's Yii\base\controller::layout property is not NULL, use it as the layout value, and the controller's Yii\base\controller::module module as the context module.
If the yii\base\controller::layout is empty, start with the controller's ancestor module (including the application) to find the first Yii\base\module::layout property is not empty module, use the module as the context module, and its yii\base The value of \module::layout as the layout value, if none is found, indicates that the layout is not used.
In the second step, it determines the value of the layout in the first step and the context module corresponds to the actual layout file, and the layout value can be:

Path aliases (such as @app/views/layouts/main).
Absolute path (such as/main): The value of the layout begins with a slash, and the actual layout file is found in the applied [[yii\base\application::layoutpath|layout Path] layout path, and the layout path defaults to @app/views/ Layouts
relative path (e.g. main): Find the actual layout file in the Yii\base\module::layoutpath layout path of the context module, default to the views/in the Yii\base\module::basepath module directory Layouts directory.
Boolean value false: Layout is not used.
The value of the layout does not contain the file name extension, which is used by default. php as the extension.

nested layouts

Sometimes you want to nest one layout to another, for example, in different places in a Web site, you want to use a different layout, and these layouts share the same basic layout that generates the global HTML5 page structure, and you can call Yii\base\view::begincontent () in a child layout and the Yii\base\view::endcontent () method, as follows:

<?php $this->begincontent (' @app/views/layouts/base.php ');? >...child layout Content here...<?php $this- >endcontent ();?>

As shown above, the sub-layout content should be passed between the yii\base\view::begincontent () and the Yii\base\view::endcontent () method, to Yii\base\view::begincontent () parameter specifies the parent layout, which can be a layout file or an alias.

Use these methods to nest layouts in multiple layers.

Working with data blocks

Data blocks can be specified in one place to display the contents of the view in another place, usually with the layout, for example, you can define a block of data in the content view to display it in the layout.

Call Yii\base\view::beginblock () and Yii\base\view::endblock () to define a block of data, using $view->blocks[$blockID] To access the data block, where $blockID The unique identification ID that is specified when the data block is defined.

The following example shows how to use a block of data in a content view for layout use.

First, you set one or more blocks of data in the content view:

<?php $this->beginblock (' Block1 ');? >...content of Block1...<?php $this->endblock ();? >...<? PHP $this->beginblock (' Block3 ');? >...content of Block3...<?php $this->endblock ();?>

Then, in Layout view, data blocks are rendered if they are available, and some default content is displayed if the data is undefined.

<?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:?>  ... the default content for Block3 ... <?php endif;

Working with View components

The Yii\base\view view component provides many view-related features that create Yii\base\view or its subclass instances to get the view component, mostly using the View application component, which can be configured in the app configuration as follows:

[  // ...  ' Components ' = ' + [    ' view ' = '      class ' = ' App\components\view ',    ],    //...  ],

The view component provides the following useful view-related features, each of which is described in a separate section:

    • Subject: Allows you to develop and modify themes for your Web site;
    • Fragment caching: Allows you to cache fragments in a Web page;
    • Customer script Processing: Support CSS and JavaScript registration and rendering;
    • Resource Package Processing: Support the registration and rendering of resource bundles;
    • Template engine: Allows you to use other template engines, such as Twig, Smarty.

When developing Web pages, it is also possible to use the following useful small features frequently.

Set Page title

Each web page should have a title, the label of which is normally displayed in the layout, but in fact the title is mostly determined by the content view rather than the layout, and to solve this problem, Yii\web\view provides yii\web\view::title The Caption property allows the header information to be passed from the content view to the layout.

To take advantage of this feature, set the page title in each content view, as follows:

<?php$this->title = ' My page title ';? > Then in the view, make sure that the  following code is in the segment:<?= Html::encode ($this->title)?>

Register META META Tags

Web pages often need to generate various meta tags to provide to different browsers, such as the page titles in, meta tags are usually generated in the layout.

If you want to generate meta tags in the content view, you can call the Yii\web\view::registermetatag () method in the content view as follows:

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

The code above registers a "keywords" meta tag in the view component, renders the registered meta tag after the layout is rendered, and then inserts the following HTML code into the layout called the Yii\web\view::head () method:

 
  

Note If you call the Yii\web\view::registermetatag () method multiple times, it registers multiple meta tags and does not check for duplicates when registering.

To ensure that there is only one per meta tag, you can specify the key as the second parameter when calling the method, for example, the following code registers two "description" meta tags, but only the second one is rendered.

$this->registermetatag ([' name ' = ' description ', ' content ' = ' This is my Cool website made with yii! '], ' descrip tion '); $this->registermetatag ([' name ' = ' description ', ' content ' = ' This website are about funny raccoons. '], ' Description ');

Register link Label

Like meta tags, link tags are sometimes useful, such as customizing website icons, specifying RSS feeds, or authorizing OpenID to other servers. You can call Yii\web\view::registerlinktag () in a similar way to a meta tag, for example, registering a link tag in the content view is as follows:

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

The code above is converted into

Copy the Code code as follows:


Similar to Yii\web\view::registermetatag (), call Yii\web\view::registerlinktag () to specify the key to avoid generating duplicate link labels.

View Events

The Yii\base\view view component triggers several events during the view rendering process and can respond to these events to add content to the view or adjust rendering results before the content is sent to the end user.

    • Yii\base\view::event_before_render: Triggered at the beginning of the controller render file, the event can be 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, which gets the rendered result of yii\base\viewevent::output. You can modify the property to modify the rendering results.
    • Yii\base\view::event_begin_page: Triggered when the layout calls Yii\base\view::beginpage ();
    • Yii\base\view::event_end_page: In the layout call Yii\base\view::endpage () is triggered;
    • Yii\web\view::event_begin_body: Triggered when the layout calls Yii\web\view::beginbody ();
    • Yii\web\view::event_end_body: Triggered when the 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 ');});

Render a static page

Static pages refer to Web pages where most of the content is static and does not require a controller to deliver dynamic data.

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

Public Function Actionabout () {  return $this->render (' about ');}

If the Web site contains a lot of static pages, repeating similar code multiple times is cumbersome, to solve this problem, you can use a separate 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 under the @app/views/site/pages directory named about, you can display the view by Rul as follows:

Http://localhost/index.php?r=site/page&view=about
The GET in view parameter tells the yii\web\viewaction operation which view to request, and then the operation looks for the view under the @app/views/site/pages directory, which can be configured Yii\web\viewaction::viewprefix Modifies the directory of the search view.

Best practices

The view is responsible for presenting the model's data to the format the user wants, in short, the view

    • Should mainly include the display code, such as HTML, and simple PHP code to control, format and render the data;
    • You should not include execution data query code, which is placed in the model;
    • Direct access to request data should be avoided, such as $_get, $_post, which should be performed in the controller and, if requested, should be pushed to the view by the controller.
    • Model properties can be read, but they should not be modified.
    • To make the model easier to maintain, avoid creating views that are too complex or contain too much redundant code, you can achieve this by following these methods:
    • Use layouts to show common code (e.g., page header, tail);
    • The complex views are divided into smaller views, which can be rendered and assembled into a large view using the rendering method described above.
    • Create and use widgets as data blocks for views;
    • Create and use helper classes to transform and format data in a view.

Articles you may be interested in:

    • A detailed description of the use of the front-end resource bundle in PHP's YII framework
    • Introduction to some advanced usage of caching in the YII framework of PHP
    • In-depth parsing of PHP's caching capabilities in the YII framework
    • A detailed approach to creating views and rendering views in the PHP yii framework
    • A tutorial on model models in the YII framework of PHP
    • Controller controllers in the YII framework of PHP
    • The method of removing the binding behavior of a component in PHP's YII framework
    • The definition and binding methods of behavior in the YII framework of PHP
    • In-depth explanation of properties in the Yii framework of PHP
    • A detailed description of the installation and use of PHP's YII framework Extension

http://www.bkjia.com/PHPjc/1117071.html www.bkjia.com true http://www.bkjia.com/PHPjc/1117071.html techarticle PHP in the YII framework of the use of view view in the Advanced, Yiiview view name rendering view, you can specify a view name or view file path/alias, in most cases, the former because the former Jane ...

  • 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.