YII pass parameters to templates

1. First save the parameters in the controller

[php]  view plain copy  
  1. publicfunction actionAbout()   
  2.     {  
  3.         $view  = Yii:: $app ->getView(); //The view instance here is the same as the view in the view (default $this variable). So the parameters saved here can also be used in the view  
  4.         $view ->params[ 'testView' ] =  'testView' //Because it is the same layout variable, it can also be used in the view  
  5.         //$this->renderAjax('about',['test'=>7]);  
  6.         //$this->renderFile('app\views\site\about.php',['test'=>8]);  
  7.         return$this->render('/site/about.php',['test'=>5]);   
  8.     }  

2. Use it in the view

[php]  view plain copy  
  1. echo$this->params['testView'];   

3. Pass the data summary to the view:

Access data in view

There are two ways to access data in views: 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 an array of name-value. When the view is rendered, the PHP  extract() method is called to convert the array into a variable accessible to the view. For example, the following controller's render view code pushes 2 variables to the  report view: $foo = 1 and  $bar = 2.

[php]  view plain copy  
  1. echo$this->render('report', [   
  2.     'foo' => 1,  
  3.     'bar' => 2,  
  4. ]);  

The pull method allows the view to actively obtain data from the yii\base\View view component or other objects (such as Yii::$app), and the controller ID can be obtained by using the following expression $this->contextin the view, allowing you reportto obtain any data of the controller in the view. Property or method, such as the following code to get the controller ID.

[php]  view plain copy  
  1. The controller ID is: <?= $this->context->id ?>  

The push method makes the view less dependent on the context object, and is the preferred method for the view to obtain data. The disadvantage is that it needs to manually construct the array, which is somewhat cumbersome and prone to errors when rendering in different places.

Share data between views

The yii\base\View view component provides the yii\base\View::params parameter property to allow different views to share data.

For example, in a aboutview, you can use the following code to specify the current part of the current breadcrumbs.

[php]  view plain copy  
  1. $this->params['breadcrumbs'][] = 'About Us';  

In a layout file (which is also a view), display breadcrumbs can be generated using the values ​​added to the yii\base\View::params array in turn:

[php]  view plain copy  
  1. <?= yii\widgets\Breadcrumbs::widget([  
  2.     'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],  
  3. ]) ?>  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324731834&siteId=291194637