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 4 Colors

Bootstrap 4 Colors Bootstrap 4 consists of classes that are used to set colors according to the context of the element, and with the help of these classes, we can read...

2 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 With CSS

← Prev Next → ...

1 minute read.

Bootstrap 4 Collapse

Bootstrap 4 Collapse Collapse is a bootstrap component that is similar to the dropdown button. Collapse is used to hide or show the content such as paragraphs, sentences, etc.  When we click on a...

4 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.

Difference between bootstrap.css and bootstrap-theme.css

The "bootstrap.css" uses to create a website with pre-existing designs and context. It uses basic Bootstrap classes like rows and columns with a CSS styling tool. The website is styled...

5 minutes read.

Bootstrap Protocol (BOOTP)

In the following article, we will learn about the Bootstrap Protocol and how it maintains contracts among linked devices on webwork. What is Bootstrap Protocol? The Bootstrap Protocol is a webwork contract...

3 minutes read.

Bootstrap Tabs and Pills

Bootstrap Menus Bootstrap menu is used to create different types of menu. It can created horizontal with its .list-inlineclass. <div class="container">       <h3>Example of Bootstrap Menu</h3>       <ul class="list-inline">         <li><a href="#">Home</a></li>         <li><a href="#">About</a></li>         <li><a href="#">Contact</a></li>         <li><a href="#">services</a></li>       </ul>     </div> Try Now Bootstrap Tabs Bootstrap tabl is look like is menu but there is some difference....

4 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.

Bootstrap Toast Example

What are toasts? Toasts are similar to notifications, and they are lightweight and act as push notifications from mobile and desktop operating systems. They’re built using flexbox in Bootstrap. They can...

4 minutes read.

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 Pagination

Bootstrap 4 Pagination Bootstrap pagination is used to show the existence of a series of web pages of the website. It allows navigation on multiple pages of a website. In pagination, there is a block...

9 minutes read.

Bootstrap 4 Modal

Bootstrap 4 Modal The Modal is a component of Bootstrap 4, which is a dialog box or pop-up window. The modals are used to provide information or warning to the user, such as...

18 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.

Text Shadows in CSS

Text shadows are created with the text-shadow CSS property. It takes a list of shadows separated by commas to be applied to the text and any of its styles. Each...

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 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 4 Progress Bar

Bootstrap Progress Bar Bootstrap 4 offers progress bars that are used to represent the progress of tasks such as downloading a file, software installation, etc. on the computer. It represents the percentage of the...

9 minutes read.

Bootstrap 4 Icons

Bootstrap 4 Icons Bootstrap 3 contains the default icon library. But in bootstrap 4, you have to include the external icon library by yourself. Many free icon libraries are available such...

2 minutes read.