布局
首先创建一个布局文件simple.php,路径是在views/layout/目录下。
<p>this is header</p>
<?= $content ?>
<p>this is footer</p>
为HelloController创建两个视图文件
views/hello/about.php
this is about.php , data => <?php echo $data;?>
views/hello/index.php
this is index.php , data => <?php echo $data;?>
创建一个控制器
简单的HelloController
<?php
namespace app\controllers; use Yii;
use yii\web\Controller; class HelloController extends Controller { public $layout = "simple"; public function actionIndex()
{
return $this->render("index", ["data" => "hello world"]);
} public function actionAbout()
{
return $this->render("about", ["data" => "hello yii2"]);
}
}
测试
访问localhost/basic/web/index.php?r=hello/index,可以看到如下结果:
访问localhost/basic/web/index.php?r=hello/about,可以看到如下结果:
某个视图中加载另外一个视图
假设是index.php视图中要显示about.php视图,可以这样做:
this is index.php , data => <?php echo $data;?>
<br>
<?php echo $this->render("about", ["data" => "hello demo"]) ?>
访问localhost/basic/web/index.php?r=hello/index,可以看到如下结果: