CakePHP Layouts & Elements

A layout includes a presentation code that can be wrapped out in your view. It means that what you want to see in your view should be well-positioned in layout. When you create a layout file, then you have to tell CakePHP where you can place the data of your view code, which can be rendered by the controller, and CakePHP's default layout is located at src/Template/Layout/default.ctp. While creating a layout for your application, you have to make sure that it includes this syntax “$this->fetch('content');” for fetching the content.

<?=
$this->fetch('content')?>                
//it displays the content from the current rendered //view file of .ctp 

Or

You can also define php syntax like this:

<?php echo $this->fetch('content'); ?>

If you have used this syntax "<?= ?>" for printing any text, then you don’t need to write php as well echo; it considered by default in php.

The default file loaded all the content of the template’s action file that can be rendered on the browser. The dafault.ctp file contains the default page layout for the CakePHP application, and if you want to modify the page, then you can change by going to Layout/default.ctp

<div class="container clearfix">
         <?= $this->fetch('content') ?>
</div> 

The above function exists in default.ctp file for fetching the content in controller.php file with the use of fetch(‘content’) function.

Now we are going to create a program using the layout in the controller file. For this, we have to require three files.

  1. SecondController.php file
  2. fun3.ctp file
  3. And the last fun3layout.ctp file

This is the fun3layout.ctp (default file) which loads all the content of controller.php file.

 <!DOCTYPE html>
 <html>
 <head>
    <title><?php echo $title;  ?> </title>                
    </head>
 <body>
     <header>This is my first custom layout line </header>
                <div class="container clearfix">
         <?= $this->fetch('content') ?> // This is a method function which fetch all the content of layout in web.
     </div>
     <footer>This is the last line of custom footer
     </footer>
 </body>
 </html> 

For loading the layout function in a controller, we have to create a constructor and pass the fun3layout.ctp file in the layout function of the Controller, or you can modify the default.ctp file according to your need, which is defined in layout/default.ctp and then calls it at the controller.

Here, we have created the SecondController.php file in the Controller folder.

<?php
                namespace App\Controller;
                use App\Controller\AppController;
                class SecondController extends AppController
                                { 
                         public function initialize()                              
                      {        // we have created a constructor for loading the layout in controller.
                      parent:: initialize();
                    $this-> viewBuilder()-> layout(‘fun3layout’);
                }
                                public function fun3()
                                               {
                               $this->set('name','suresh')            
                             $this->set("tutor", "mahesh" );                
                                  $this->set('title' , 'This is first custom layout');
                            }
                }
 ?> 

Now we have to create fun3.ctp file in Second folder of Template folder and write the given below program in your fun3.ctp file.

<p> WELCOME TO THE Tutorial and Example. IT IS AN ONLINE LEARNING TUTORIAL 
 FOR IT PROFESSIONAL.
 <br/>
   name: <?php  echo $name; ?>
 <br/>
 Tutor <?php  echo $tutor; ?>
 </p> 

Output

CakePHP Layouts & Elements

View Elements

Elements are the small block of layout code, that can be re-used in any page by calling in default.ctp  or layout.ctp file to avoid re-writing code.

  • It is like ad boxes, sliders, navigation, etc.
  • It can be considered as mini-view.
<?php
            echo $this->element('navbar');    // we can pass the view file by use of element function
?> 

Here, we have created the SecondController.php file in the Controller folder.

 <?php
                namespace App\Controller;
                use App\Controller\AppController;
                class SecondController extends AppController
                                { 
                         public function initialize()                              
                      {        // we have created a constructor for loading the layout in controller.
                      parent:: initialize();
                    $this-> viewBuilder()-> layout(‘fun3layout’);
                }
                                public function fun3()
                                               { 
                               $this->set('name','suresh')            
                             $this->set("tutor", "mahesh" );                
                                  $this->set('title' , 'This is first custom layout');
                            }
                }
 ?> 

This is the file of fun3layout.ctp at src\Template\Layout\fun3layout.ctp file.

 <!DOCTYPE html>
 <html>
 <head>
    <title><?php echo $title; ?> </title>             
    </head>
 <body>
      <?= $this->element("headerElement") ?>   //element method which is used for passing element file to headerElement file
             <div class="container clearfix">
           <?= $this->fetch('content') ?>
          </div>
         <?= $this->element("footerElement")  ?>
 </body>
 </html> 

Now we have to create headerElement.ctp file for setting the header in web application.

 <header>This is my first custom layout line 
 <br/>This is the second line of element file which we have passed in element function with this syntax:
  <b> $this->element("headerElement") </b>
 </header> <br/> 

Similary, we have created “footerElement.ctp” file for set the footer in web page.

 <footer>This is the last line of custom footer.
  <br/> This is the last line of element file which we have passed in element function
 with this syntax:   <b> $this->element("footerElement") </b> </footer><br/> 

Output

CakePHP Layouts

View Events

Here we have described several callbacks/events that can be used in a view. In CakePHP, event controllers are helpful in performing multiple tasks before or after an action. CakePHP contains a list of viewing events as follows.

Events Function and Description

  • Helper::beforeRender(Events $event, $viewFile) 

The beforeRender function will be called after the Controller’index, but before the controller renders view and layout. This function will render the file as an argument.

  • Helper::beforeRenderFile(Event $event, $viewFile)

The function will call before each view file is rendered. This function will include elements, view, parent view, and layouts.

  • Helper::afterRenderFile(Event $event, $viewFile, $content)

The method will call after each View file is rendered. This function includes elements, views, parent views, and layouts. A callback/events can be modified and return the $content for representing the content in the browser.

  • Helper::afterRender(Event $event, $viewFile) 

This method will be called after the view file is rendered, but before the layout rendering method start.

  • Helper::beforeLayout(Event $event, $layoutFile)

This method will be provided before the layout starts and get the filename as an argument.

  • Helper::afterLayout(Event $event, $layoutFile)

The view helper function will be called after the layout render is complete and get the filename as an argument.


Related Topics

Bootstrap Navigation bar

Navigation Bars In Bootstrap, We can create navigation bar like a navigation header. It is placed at the top of the page. We can collapse or extend it according to screen...

3 minutes read.

Bootstrap 4 Tooltip

Bootstrap 4 Tooltip Tooltip Bootstrap 4 offers a tooltip component, a small popup box that appears when you move the cursor over an element such as buttons or any highlighted element. It...

3 minutes read.

Difference between Bootstrap and WordPress

What is WordPress? WordPress is a free open-source CMS (Content Management System) that is written using Hypertext Pre-processor (PHP) and is paired with MySQL and is supported with HTTPS (Hypertext Transfer...

3 minutes read.

Bootstrap 4 Utilities

Bootstrap 4 Utilities Bootstrap 4 utilities also known as helper classes that are used to add more style to the components. Utilities are used to make the website or webpage more stylish or elegant....

10 minutes read.

Bootstrap 4 Toast

Bootstrap 4 Toast Bootstrap 4 offers a Toast component, which is quite similar to the alert box and pushes notifications. The toast is visible on the screen for a few seconds when any...

5 minutes read.

Bootstrap 4 Margin classes

Bootstrap 4 contains a variety of brief, responsive margin and padding utility classes to change the appearance of an element. The Bootstrap 4 margin classes use for the outer spacing of...

8 minutes read.

Bootstrap 4 Carousel

Bootstrap 4 Carousel Bootstrap 4 offers a carousel component, which is also known as a slider or slideshow. The carousel is used for the dynamic representation of content using images with...

7 minutes read.

Bootstrap Pager

← Prev Next → ...

1 minute read.

Bootstrap 4 Filters

 Bootstrap 4 Filters Bootstrap 4 provides a filter component that is used to search an element from a list, table, etc. Bootstrap does not contain any component or utility that helps...

5 minutes read.

Bootstrap 4 Layout

Containers Containers are the essential elements of the bootstrap layout. It is required when we are using a bootstrap grid system. Containers can also be nested, but most layouts do not need nested containers. Bootstrap has...

3 minutes read.

Bootstrap List group

Bootstrap list group provides a group of a list of items. The most basic list is an unordered list. We can use <ul> element with .list-group class and <li> element with .lsit-group-item. Let us see...

3 minutes read.

Dropdown & Dropup

Bootstrap Dropdowns The bootstrap dropdown menu is used to create a toggleable menu. It provides users to choose one value from a predefined list. Before creating dropdown menu, we have to know...

3 minutes read.

Bootstrap 4 Scrollspy

Bootstrap 4 Scrollspy Bootstrap 4 offers a scrollspy component that is used to make the website more attractive and eye-catching. Basically, the scrollspy is used on the single-page website. The scrollspy highlights the nav...

5 minutes read.

Bootstrap 4 Jumbotron

Bootstrap 4 Jumbotron Bootstrap offers Jumbotron, which is used to get more attention to specific content or information on the web page. It provides a gray background-color to the content to make that content...

2 minutes read.

Bootstrap Typography

Bootstrap provides simple and easily customized typography for headings, body text, lists, and many more. Headline <h1> to <h6> By default, Bootstrap has HTML headings (<h1> to <h6>) that are given below: Example <h1>h1. Bootstrap heading</h1>   <h2>h2. Bootstrap heading</h2>   <h3>h3. Bootstrap heading</h3>   <h4>h4. Bootstrap heading</h4>   <h5>h5. Bootstrap heading</h5>   <h6>h6. Bootstrap heading</h6> Try Now ←...

1 minute read.

Bootstrap Input groups

Bootstrap 4 Input groups The input group is a component of Bootstrap 4, which is used to create interactive and stylish form controls. With the help of input groups, you can easily customize the input...

8 minutes read.

Bootstrap 4 navbar

A navigation navbar or navbar uses in every website to make it more user-friendly. Navigating through the website is easier, and the user can instantly search for the topic of...

8 minutes read.

Bootstrap 4 Content

Typography Typography is used for styling and formatting the content. It also helps in creating customized headings, sub-headings, lists, paragraphs, etc. Headings Bootstrap 4 offers HTML heading <h1> to <h6> that has bolder...

8 minutes read.

Bootstrap Badges and Labels

Bootstrap Badges Bootstrap Badges are numerical indicators. It is used to show that how many items are associated with a link.The .badge class is used to create of Bootstrap Badges. Let us see...

2 minutes read.

Bootstrap 4 Form

Bootstrap 4 Forms Bootstrap 4 provides forms, which are one of the essential components for web pages and web applications. It is an input-based component, used to collect user data with the help of...

8 minutes read.