简体   繁体   中英

Change layout file within a view in Yii2

I am doing a small project using Yii2.

Suppose I have same layout (header, footer) in a view (eg site ) except a login.php in this view. I want a different or no header / footer in this file. What can I do the remove the header / footer only from this view file.

All I could get to change layout in different views. Is it possible to change layout in a single file of a view?

Inside the relative action:

public function actionYourAction($id)
{

    $this->layout = 'yourNewLayout';

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

I am a little late to the party, but you CAN change your layout from within your view. You do not have to declare it in your controller. I personally think it is better to do it in the view, because you can easily see later what is going on. If your making HTML edits, you would go into the view file, and easily be able to see which layout it is using. Putting this in the Controller, you (or someone later on) might miss the layout change nested into your controller's action.

Since $this refers to your view in Yii2 and not your controller as it did in Yii1, the old $this->layout doesn't work anymore from within your view.

Now, in Yii2, you refer to the controller from your view using $this->context .

$this->context->layout = 'your-layout';

In my project I wanted 2 layouts: one for site and one for the webapp. As the main.php file is the default layout, I've created a site.php layout and in the beginning of the siteController, just after the class declaration, I've put

public $layout = 'site';

The result is that only the siteController rendered views are using the site.php layout. It worked for me.

I'm also a litte late to the party, but struggled with this stuff today... To me, to create a separate layout just because I want to skip the footer or header seems like much code for little win. If I can stick to the main layout, I can just get at the controller and the action currently loaded, and have it omitted this way (write this in main.php):

$contr   = Yii::$app->controller->id;
$action  = Yii::$app->controller->action->id;
$skipFooter = $contr == 'site' && $action == 'login'; //...or enter here   what U want

... and then later:

<?php if (!$skipFooter): ?> //Never at login...
    <footer class="footer">
        <div class="container">
            <p class="pull-left">&copy; YourSite.com <?= date('Y') ?></p>

            <p class="pull-right"><?= Yii::powered() ?></p>
        </div>
    </footer>
<?php endif; ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM