Yii框架布局文件的动态切换操作示例
这篇文章主要介绍了Yii框架布局文件的动态切换操作,结合实例形式分析了Yii框架控制器动态切换布局的相关实现技巧,需要的朋友可以参考下
本文实例讲述了Yii框架布局文件的动态切换操作。分享给大家供大家参考,具体如下:
如果你看了底层Controller的源码和Module(模块)的源码,那么你就能很熟练的婉转布局切换了。
1、在控制器中切换当前布局和在方法中动态切换布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | <?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 达到切换布局的目录。
甚至我们可以在模块文件中声明布局
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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布局了。