關於在Yii1.x的版本中變量的傳遞能夠查看這個:在Yii框架中,控制器如何傳遞變量給layouts裏的模板,下面說說在Yii2.0中的實現方法。php
在Yii2.0中,view模板文件裏面的$this已經不是對應的控制器對象了,而是View對象的變量。咱們能夠經過View對象中的params變量來傳遞數據。
先獲取當前View,而後給view設置參數,html
class SiteController extends Controller
{
public function actionIndex()
{
//設置當前view的params參數,
$view = Yii::$app->view;
$view->params['layoutData']='test';
return $this->render('index');
}
}web
在layouts/main.phpbootstrap
<?php
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use frontend\assets\AppAsset;
use frontend\widgets\Alert;
/**
* @var \yii\web\View $this
* @var string $content
*/
AppAsset::register($this);
?>
<?php $this->beginPage() ?>
<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
<meta charset="<?= Yii::$app->charset ?>"/>
<title><?= Html::encode($this->title) ?></title>
<?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>
<?php echo $this->params['layoutData']?>
..............app
view裏面的$this由控制器對象變爲View對象是其中的一個大改變,這樣整個框架也更清晰了。框架