How To Define Layout In Cake PHP

Layout refers the hows your website looks, the Layout defines your header and footer with content area. Anything you want to see in all of your views should be placed in a layout. Layout files should be placed in /app/views/layouts.

You can define your custom layout as well and place it into the '/app/views/layouts' folder. Cake PHP also provides the functionality to override the default layout, to override layout you need to create a default.ctp file and placed into layout folder.

now whenever the controller rendered a view your content will be placed inside of the default layout.

The cake PHP has inbuilt following Layouts for HTML content:

1- default layout
2- ajax
3- flash

As per the layout name,

The default layout is responsible for general HTML render.

The ajax is responsible for handling ajax requests and sending response simple content without a header and footer.

The flash layout is used for messages shown by the controller’s flash() method.

How to define custom layout in cake PHP:

Create a custom layout we make sure the layout folder should include a place for $content_for_layout (and optionally, $title_for_layout).

A simple example of a custom layout is below:

Step 1: create custom.ctp file and placed it into the layout folder.

<title><?php echo $title_for_layout?></title>
 	<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<!-- Include external files and scripts here (See HTML helper for more info.) -->
<?php echo $scripts_for_layout ?>



<!-- If you'd like some sort of menu to show up on all of your views, include it here -->

<div id="header">

<div id="menu">...</div>

</div>


<!-- Here's where I want my views to be displayed -->
<!--?php echo $content_for_layout ?-->

<!-- Add a footer to each displayed page -->

<div id="footer">...</div>

$scripts_for_layout : This variable contains any external files and scripts included with the built-in HTML helper.
$content_for_layout: This variable contains the view.
$title_for_layout: This variable contains the page title.

Step 2:Call this layout in the controller action.

class UsersController extends AppController {
    function viewUsers() {
        $this->set('title_for_layout', 'View Users');
        $this->layout = 'custom';
    }
}

title_for_layout: This variable is used to set the title for view.
$this->layout: This variable is used to set the layout file.

Leave a Reply

Your email address will not be published.