Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 How to split layout file to separate header and footer?

Tags:

php

yii2

I am new to YII2, so this can be very basic question.

I have set up initial application. I have setup theme for my YII2 application /themes/standard

Now, There is a default layout file themes/standard/layouts/main.php - This has the html code for header and footer

I want to separate the header code into themes/standard/layouts/header.php and footer into another file

I tried something like below code in main.php

<?php $this->render("header"); ?>

tried this as well

<?php $this->render("//layouts/header"); ?>

But It doesn't render the content. I don't want to absolute path since I have theming Can you people help with this one?

like image 206
Samura Avatar asked Dec 18 '14 11:12

Samura


1 Answers

In order to have Nested Layouts, You can use beginContent() and endContent() like below(In your main.php layout for example):

<?php $this->beginContent('@app/views/layouts/header.php'); ?>
    <!-- You may need to put some content here -->
<?php $this->endContent(); ?>

Everything between begin and end will be replaced wit $content in header.php.


As of Yii2's official example:

Sometimes you may want to nest one layout in another. For example, in different sections of a Web site, you want to use different layouts, while all these layouts share the same basic layout that generates the overall HTML5 page structure. You can achieve this goal by calling beginContent() and endContent() in the child layouts like the following:

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

...child layout content here...

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

As shown above, the child layout content should be enclosed within beginContent() and endContent(). The parameter passed to beginContent() specifies what is the parent layout. It can be either a layout file or alias. Using the above approach, you can nest layouts in more than one levels.

http://www.yiiframework.com/doc-2.0/guide-structure-views.html#nested-layouts

like image 140
Ali MasudianPour Avatar answered Oct 02 '22 02:10

Ali MasudianPour