本文实例讲述了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布局了。