Using Custom Layout

In Yii 1.x you could use different layouts (column1, column2 etc.), is it possible to do this in Yii 2.0 as well (in one way or another)?

When a user is logged in on my website, on all pages a sidebar needs to be displayed.

Two options i have thought of:

  • I can check in every view file if a user is logged in and use a partial render to render the sidebar, but that seems very inefficient.

  • I already created my own View class (extending the yii\web\View class). I can create a function here which will check if a user is logged in, and if so, partial render the sidebar view. But i still have to call this function in every view file then.

Or is there another handy way to do this?

Sure.

See $layout property of yii\base\Controller.

Also you can set different layouts for modules etc.

How about creating a widget?

Thanks, can i also use (like in Yii 1.x) something like beginContent() and endContent(), so i can use my ‘main’ layout as the base for another layout?

What i uses in Yii 1.x:


<?php $this->beginContent('//layouts/main'); ?>

<div id="content">

	<?php echo $content; ?>

</div><!-- content -->

<?php $this->endContent(); ?>

Yes, this is called Block widget now.

How can i use the Block widget to create a layout based on the main layout?

If you mean template inheritance, see other templating engines like twig or smarty. AFAIK default engine does not support this.

Ah thanks, well, this works (it partial renders the main layout):

layouts/main2.php:


echo $this->render('//layouts/main', ['content' => $content]); 

But it’s not very nice, since you need to pass the extra html in $content this way.

I think i’m going for the widget way (put my sidebar inside a widget and call it in the main layout)

Edit, did it like this:

In my base controller i added a


public $partialLayout = null;

so i can set this in my controllers.

In my main layout i used this:


<?php if ($this->context->partialLayout !== null): ?>


                <?php echo $this->render('//layouts/'.$this->context->partialLayout, ['content' => $content]); ?>


            <?php else: ?>


                <?php echo $content; ?>


            <?php endif; ?>

Yii2 is pretty good with layouts handling as well and can do what Yii 1 had but with more features. Trick is to use the aliases for paths, when you want to create a layout embedded in another layout file for example:

[html]

<?php $this->beginContent(’@app/views/layouts/main.php’); ?>

<div>Your layout content here</div>

<?php $this->endContent(); ?>

[/html]

I see, couldn’t find the beginContent / endContent ;) thanks!