向View传值
最后更新于:2022-04-01 11:16:45
### Models, Views, Controllers
>[info] http://www.yiichina.com/doc/guide/2.0/structure-overview
![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2015-10-10_561892e50429e.png)
### 向View传递Model
>[info] 项目代码下载 https://git.oschina.net/radarxu/yii-demo
1、简单模型
frontend\controllers\SiteController.php
~~~ php
public function actionAbout()
{
$location = '中国,上海';
return $this->render('about', ['location' => $location]);
}
~~~
frontend\views\site\about.php
~~~ html
/* @var $location string */
<p>地址: <?= $location ?></p>
~~~
2、数组模型
frontend\controllers\SiteController.php
~~~ php
public function actionAbout()
{
$location = ['city' => '上海', 'country' => '中国'];
return $this->render('about', ['location' => $location]);
}
~~~
frontend\views\site\about.php
~~~ html
/* @var $location array */
<p>城市: <?= $location['city'] ?></p>
<p>国家: <?= $location['country'] ?></p>
~~~
3、复杂模型
frontend\controllers\SiteController.php
~~~ php
public function actionAbout()
{
$model = new AboutModel();
$model->name = '徐飞';
$model->city = '上海';
$model->country = '中国';
return $this->render('about', ['model' => $model]);
}
~~~
frontend\views\site\about.php
~~~ html
/* @var $model frontend\models\AboutModel */
<p>姓名: <?= $model->name ?></p>
<p>城市: <?= $model->city ?></p>
<p>国家: <?= $model->country ?></p>
~~~
4、多个模型
frontend\controllers\SiteController.php
~~~ php
public function actionAbout()
{
$name = '徐飞';
$city = '上海';
$country = '中国';
return $this->render('about', ['name' => $name, 'city' => $city, 'country' => $country]);
}
~~~
frontend\views\site\about.php
~~~ html
/* @var $name string */
/* @var $city string */
/* @var $country string */
<p>姓名: <?= $name ?></p>
<p>城市: <?= $city ?></p>
<p>国家: <?= $country ?></p>
~~~