Yii - 布局文件的动态切换

如果你看了底层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布局了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值