Yii2 Frame View Operation and Analysis of Layout’s Usage


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

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.



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



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.