Using advanced _php techniques in the View view in the Yii framework of PHP

Source: Internet
Author: User
Tags echo date php code yii

View Name

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

The view name can be based on the following rules to the corresponding view file path:

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

Accessing data in the view

There are two ways of accessing data in a view: Push and pull.

The push way is to pass the data through the second parameter of the view rendering method, the data format should be an array of name-value, and when the view is rendered, invoke 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 in-line view: $foo = 1 and $bar = 2.

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

The Pull method enables the view to actively obtain data from the Yii\base\view view component or other object (such as Yii:: $app), using the following expression $this->context in the view to obtain the controller ID. Allows you to get any of the controller's properties or methods in the 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 to obtain the data priority use, the disadvantage is that the need to build the array manually, some cumbersome, rendering in different places 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 portion of the current breadcrumbs.

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

In a layout file (also a view), you can generate a display breadcrumbs by using the values added to Yii\base\view::p arams Array:

<?= 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 headers and tails, and repeat the same headers and tails in each view, preferably by placing them in a layout, rendering the content view and embedding it in the layout where appropriate.

Create a layout

Because the layout is also a view, it can be created like a normal view, with the layout default stored under the @app/views/layouts path, 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 Customize the layout default path for an application or module.

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

<?php use
yii\helpers\html;

/* @var $this Yii\web\view
/////* @var $content String string
/*?>
<?php $this->beginpage ()?>
& lt;! DOCTYPE html>
 
 

As shown above, the layout generates a generic HTML tag for each page, in the <body> tab, prints the $content variable, $content variable is represented when Yii\base\controller::render () The content view rendering results that are passed to the layout when the 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 the scripts and tags that are registered elsewhere are added to the place where the method calls.

    • Yii\base\view::beginpage (): This method should be called at the beginning of the layout, triggering the Yii\base\view::event_begin_page event that indicates the beginning of the page.
    • Yii\base\view::endpage (): This method should be called at the end of the layout, triggering the yii\base\view::event_end_page time that indicates the end of the page.
    • Yii\web\view::head (): This method should be called in the
    • Yii\web\view::beginbody (): This method should be called at the beginning of the <body> tag, triggering the Yii\web\view::event_begin_body event and generating a placeholder. The HTML code (such as JavaScript) that will be registered is replaced at the beginning of the page body.
    • Yii\web\view::endbody (): This method should be called at the end of the <body> tag, triggering the Yii\web\view::event_end_body event and generating a placeholder. The HTML code (such as JavaScript) that is registered will be replaced at the end of the page body.

Accessing data in a layout

Two predefined variables are accessible in the layout: the $this and the $content, which correspond to the Yii\base\view view component similar to normal view, which contains the result of invoking 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 that is described in the section in the view that accesses the data, and if you want to pass data to the layout from the content view, you can use the methods in the section on sharing data between views.

Working with layouts

As described in the rendering section in the controller, when the controller calls the Yii\base\controller::render () method to render the view, it uses the layout to render the 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 a different layout file, which manages the layout of all controllers, and the latter overrides the former to control the layout of a single controller. For example, the following code causes the post controller to render the view using @app/views/layouts/post.php as the layout file, and if the layout property does not change, the controller defaults to using @app/views/layouts/main.php as the layout file.

namespace App\controllers;

Use Yii\web\controller;

Class Postcontroller extends Controller
{public
  $layout = ' post ';

  // ...
}

For a controller in a module, you can configure the module's Yii\base\module::layout property to specify that the layout file be applied to all controllers of the module.

Since layout can be configured at different levels (Controller, module, application), the behind-the-scenes Yii uses two steps 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 value of the layout, the controller's Yii\base\controller::module module as the context module.
If Yii\base\controller::layout is empty, start with the ancestor module of the controller (including the application) to find the first yii\base\module::layout module that is not empty, use the module as the context module, and place its yii\base The value of the \module::layout is the value of the layout, and if none is found, the layout is not used.
In the second step, it determines that the value of the layout in the first step and the context module correspond to the actual layout file, and the value of the layout can be:

Path aliases (such as @app/views/layouts/main).
Absolute path (such as/main): The value of the layout begins with a slash, 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 (such as main): finds the actual layout file in the Yii\base\module::layoutpath layout path of the context module, and the layout path defaults to the Yii\base\module::basepath module directory views/ Layouts directory.
False Boolean value: Do not use layout.
The value of the layout does not contain the file name extension, and the. PHP is used by default as the extension.

Nesting layout

Sometimes you want to nest one layout to another, for example, in different places of the Web site, you want to use different layouts, and these layouts share the same basic layout for generating a global HTML5 page structure, 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

... <?php $this->endcontent ();?>

As shown above, the child 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 either a layout file or an alias.

Use the above method to multiple nesting layouts.

Working with data blocks

A block of data can be specified in one place. The view content is displayed in another place, usually with 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 the block of data and access the block using $view->blocks[$blockID], where $blockID The unique identification ID that was specified when the data block was defined.

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

First, 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, blocks of data are rendered when the block is 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:?> ...
  default content for Block3 ...
<?php endif;?>
...

Working with View components

The Yii\base\view view component provides many view-related features, creating Yii\base\view or its subclass instances to get the view component, mostly using the View application component, which can be configured in the application 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 separate chapters:

    • Topics: Allows you to develop and modify topics for your Web site;
    • Fragment caching: Allows you to cache fragments on a Web page;
    • Client script processing: Support CSS and JavaScript registration and rendering;
    • Resource Bundle Processing: Support the registration and rendering of resource bundles;
    • Template engine: Allows you to use other template engines, such as Twig, Smarty.

When you develop a Web page, you may also use the following practical small features frequently.

Set Page title

Each web page should have a title, normally the label of the title is displayed in the layout, but in fact the title is mostly determined by the content view rather than the layout, and Yii\web\view provides yii\web\view::title for solving this problem. 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  
 

Register META META Tags

Web pages usually need to generate a variety of meta tags available to different browsers, such as page titles in

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 above code registers a "keywords" meta tag in the view component that renders the registered meta tag after the layout is rendered, and the following HTML code is inserted into the layout to invoke the Yii\web\view::head () method:

<meta name= "keywords" content= "yii, Framework, PHP" >

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

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

$this->registermetatag ([' Name ' => ' description ', ' content ' => ' This is I cool website made with yii! '], ' descrip tion ');
$this->registermetatag ([' Name ' => ' description ', ' content ' => ' This website is about funny raccoons. '], ' descrip tion ');

Register link Label

Like meta tags, link tags are sometimes useful, such as customizing site icons, specifying RSS subscriptions, or authorizing OpenID to other servers. You can invoke Yii\web\view::registerlinktag () in a similar way as a meta tag, for example, by registering the link label 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 into

Copy Code code as follows:

<link title= "Live News for Yii" rel= "alternate" type= "Application/rss+xml" href= "http://www.yiiframework.com/" Rss.xml/">


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

View Events

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

    • Yii\base\view::event_before_render: Triggered when the controller renders the file, which can be set to Yii\base\viewevent::isvalid to cancel view rendering.
    • Yii\base\view::event_after_render: triggered when calling Yii\base\view::beginpage () in the layout, which obtains yii\base\viewevent::output rendering results. You can modify this property to modify the rendering results.
    • Yii\base\view::event_begin_page: Triggered when layout calls Yii\base\view::beginpage ();
    • Yii\base\view::event_end_page: Calling Yii\base\view::endpage () in the layout is triggered;
    • 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 ');
});

Render a static page

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

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

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

If your Web site contains many static pages, repeating similar code multiple times is cumbersome, and to solve this problem, you can use a standalone 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 ' => [ c13/> ' class ' => ' yii\web\viewaction ',
      ],
    ];
  }


Now if you create a view named about in the @app/views/site/pages directory, you can display the view by using the following rul:

Http://localhost/index.php?r=site/page&view=about
The get view parameter tells the Yii\web\viewaction what view the operation requests, and then the operation looks for the view under the @app/views/site/pages directory, configurable Yii\web\viewaction::viewprefix Modify the directory for the search view.

Best practices

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

    • should primarily contain presentation code, such as HTML, and simple PHP code to control, format, and render data;
    • should not contain execution data query code, which is placed in the model;
    • should avoid direct access to request data, such as $_get, $_po ST, this should be done in the controller, if you need to request data, should be pushed by the controller to the view. The
    • can read model properties, but they should not be modified.
    • to make the model easier to maintain and avoid creating views that are too complex or contain too many redundant code, you can do this by using the layout to display common code (for example, the page head, the tail), and
    • to divide the complex view into smaller views so that Renders and assembles these small views into a large view using the rendering method described above;
    • creates and uses widgets as a data block for the view, and
    • creates and uses the helper class to transform and format data in the view.

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.