Yii - 布局文件的动态切换

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014559227/article/details/78190135

如果你看了底层Controller的源码和Module(模块)的源码,那么你就能很熟练的婉转布局切换了。

1、在控制器中切换当前布局和在方法中动态切换布局

<?php
namespace app\modules\TestModule\controllers;

use Yii;
use yii\web\Controller;

class IndexController extends Controller
{
    //在属性中声明
    public $layout = "custom1";

    public function actionIndex()
    {
        //在方法中动态切换布局
        $this->layout = "custom2";

        $this->render('index',array(
            'name' => '谭勇',
            'age'  => 22
        ));
    }
}
?>

在类属性中声明layout 会覆盖父类Controller 类中的layout 达到切换布局的目录。

甚至我们可以在模块文件中声明布局

namespace app\modules\TestModule;

use yii\base\Module;

class TestModule extends Module
{
    //当前应用主题
    private $theme = 'default';

    public function init()
    {
        //控制器文件存放目录
        $this->controllerNamespace = 'app\modules\TestModule\controllers';

        $dirname = dirname(__FILE__);

        //视图目录 (包含主题目录)
        $this->setViewPath($dirname . '/views/' . $this->theme . '/');

        //生命布局名称
        $this->layout = "common";
    }

}

然后我们就在default主题下的layouts目录中去寻找common.php布局了。

猜你喜欢

转载自blog.csdn.net/u014559227/article/details/78190135
yii
今日推荐