Change layout file within a view in Yii2

2020-06-07 06:30发布

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?

4条回答
相关推荐>>
2楼-- · 2020-06-07 06:59

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; ?>
查看更多
迷人小祖宗
3楼-- · 2020-06-07 07:10

Inside the relative action:

public function actionYourAction($id)
{

    $this->layout = 'yourNewLayout';

    return $this->render('yourView', [
        'model' =>$model,
    ]);
}
查看更多
别忘想泡老子
4楼-- · 2020-06-07 07:13

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';
查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-06-07 07:19

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.

查看更多
登录 后发表回答