View part in the MVC structure is responsible to present data in front of users. They mainly contain the HTML content and presentational PHP code.


Creating Views

Look at the About page code of basic Yii page.

  1. <?php   
  2.   
  3. /* @var $this yii\web\View */   
  4.   
  5. use yii\helpers\Html;   
  6.   
  7. $this->title = 'About';   
  8. $this->params['breadcrumbs'][] = $this->title;   
  9. ?>   
  10. <div class="site-about">   
  11.     <h1><?= Html::encode($this->title) ?></h1>   
  12.   
  13.     <p>This is the About page. You may modify the following file to customize its content:</p>   
  14.   
  15.     <code><?= __FILE__ ?></code>   
  16. </div>   

And it's output is this:

YII Views 1

In the above script, PHP code is used to generate the dynamic content in title and inside the form tag. HTML tags displays the data in a presentation view.


View Conventions

  • Views rendered by a controller should be written into @app/views/controllerID folder.
  • Views rendered by a widget should be written into widgetPath/views folder.

Following controller methods can be called to render views within controller:

  • render() : Renders the mentioned view file and applies a layout.
  • renderPartial() : Renders the mentioned view but without applying a layout.
  • renderAjax() : Renders a view without a layout and injects all registered JS scripts and CSS files.
  • renderFile() : Renders a view file in the specified path.
  • renderContent() : Renders a static ring.

Following controller methods can be called to render views within another view:

  • render() : Renders a view page.
  • renderAjax() : Renders a view without a layout and injects all registered JS scripts and CSS files.
  • renderFile() : Renders a view file in the specified path.

Following controller methods can be called to render views within widgets:

  • render() : Renders a view page.
  • renderFile() : Renders a view file in the specified path.

Example:

Step 1 Inside views/site folder, we are creating a view file exm.php file.

  1. <!DOCTYPE html>   
  2. <html>   
  3. <head>   
  4.     <title></title>   
  5. </head>   
  6. <body>   
  7.     <h1>Hello, welcome to JavaTpoint.</h1>   
  8. </body>   
  9. </html>  

Step 2 Render exm.php view file in the about.php view file in the site folder.

  1. <?php   
  2.   
  3. /* @var $this yii\web\View */   
  4.   
  5. use yii\helpers\Html;   
  6.   
  7. $this->title = 'About';   
  8. $this->params['breadcrumbs'][] = $this->title;   
  9. ?>   
  10. <div class="site-about">   
  11.     <h1><?= Html::encode($this->title) ?></h1>   
  12.   
  13.     <p>This is the About page. You may modify the following file to customize its content:</p>   
  14.   
  15.      <?= $this->render("exm") ?>   
  16.   
  17.     <code><?= __FILE__ ?></code>   
  18. </div>   

Step 3 Run it on the browser.

YII Views 2