Yii2 Frame View Operation and Analysis of Layout’s Usage

Time:2019-10-3

This article illustrates the Yii2 Framework View operation and the use of Layout. Share for your reference, as follows:

Render view

1. We demonstrated in Default Controller

<?php
namespace app\controllers;
use yii\helpers\Url;
use yii\web\Controller;
class DefaultController extends Controller
{
  public function actionIndex()
  {
//    echo Url::toRoute(['index','id'=>11],true);
//    //http://localhost/yiipro/web/default/index?id=11
//
//    echo Url::base();
//    ///yiipro/web
    // Return View
    return $this->render('index');
  }
}

return $this->render('index');That’s rendering the view.

2. Browser accesshttp://localhost/yiipro/web/index.php/default/We found that the report was wrong.

这里写图片描述

views/default/index.php

Explain that the view file should be placed inviews/default Under the directory.

Let’s create the view.

这里写图片描述

Visit again:

这里写图片描述

3. How to pass variables to views

Return $this - > render ('index', ['username'=>'Zhangsan','age'=> 22]);

<p><?php echo \yii\helpers\Html::encode($username); ?></p>
<p><?php echo \yii\helpers\Html::encode($age); ?></p>

这里写图片描述

Layout layout

1. Default layout

这里写图片描述


yii\base\Application::$layout = 'main'
app\module\admin\Module::$layout = 'main';

Without layout, add attributes to the controllerpublic $layout = false
Or dynamic modification in methods$this->layout = false
It can also be used$this->renderPartial()replace$this->render()

2. New Layout

View/layout/default.php

这里写图片描述

We’re going to use this layout in the Default controller and write:


public $layout = 'default';

Browser effect:

这里写图片描述

Readers interested in Yii-related content can see the topics of this site: Introduction to Yii Framework and Common Skills, Summary of Excellent Development Framework of php, Basic Course of Introduction to Smrty Template, Introduction to Php Object-Oriented Programming, Summary of Usage of Php String, Introduction to php+mysql Database Operations, and Common Database Operations of php. Summary of Skills

I hope that this article will be helpful to the PHP program design based on Yii framework.