Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change default layout for ALL controllers in Yii2?

Tags:

php

yii2

How do I change the default layout globally (= for all controllers and views) in Yii2? I want to leave the main.php layout as is in case I want to use it later.

like image 204
TheStoryCoder Avatar asked Feb 15 '16 11:02

TheStoryCoder


3 Answers

In root of configuration you can write default layout [[\yii\base\Application::$layout]] for all views:

[
     ...
     'layout' => 'main',
     'components' => [
     ...
     ]
]
like image 110
Onedev_Link Avatar answered Nov 04 '22 22:11

Onedev_Link


Configure layout & layoutPath in Yii2 config:

$config = [
    ...
    'layoutPath' => '@app/views/layouts2',
    'layout' => 'main2.php',
];

Above example changes default view app/views/layouts/main.php to app/views/layouts2/main2.php.

Yii2 Application Structure > Application

like image 39
Nick Tsai Avatar answered Nov 05 '22 00:11

Nick Tsai


You can do in the following way. For example a defaultLayout.php layout can be created like this:

<?php $this->beginContent('@app/views/layouts/main.php'); ?>
    <div class="container">
        <div class="row">
            <div class="col-lg-4">Left Side Bar</div>

            <div id="content" class="col-lg-4">
                <?php echo $content; ?>
            </div><!-- content -->

            <div class="col-lg-4">Right Side Bar</div>
        </div>
    </div>
<?php $this->endContent(); ?>

Inside the relative action

public function actionIndex()
{
    $this->layout = 'defaultLayout';

    return $this->render('index', [
        'model' =>$model,
    ]);
}

In configuration(config/main.php) you can overwrite the default layout for all your views

[
    // ...
    'components' => [
        'view' => [
            'layout' => 'main.php'
        ],
        // ...
    ],
]
like image 45
Selvakumar Kaliyappan Avatar answered Nov 04 '22 23:11

Selvakumar Kaliyappan