CakePHP 4 How To Create Custom Layout Tutorial

Reading Time: 6 minutes
3,755 Views

In this article we will see the concept of CakePHP 4 How to create custom layout. When we work with CakePHP templates for user interfaces, then layouts concept is very useful. By default CakePHP assign default.php as a parent layout for all templates inside application.

Inside this classified information we will understand how to create custom layout and load inside application. We can create our own HTML structure with all stuffs like for css, js, etc into it.

A layout simply means render dynamic content inside it. We have two different concepts about views files as Layout and Template in CakePHP.

Templates are those files which is responsible for page wise representation. For example in Contact Us page we see a contact form. In Services page we see our services.

Layout contains the common section to load with each template files. For example header section, sidebars, footer, etc.

Learn More –

Let’s get started.

CakePHP 4 Installation

To create a CakePHP project, run this command into your shell or terminal. Make sure composer should be installed in your system.

$ composer create-project --prefer-dist cakephp/app:~4.0 mycakephp

Above command will creates a project with the name called mycakephp.

Create a Master Layout

Create a file with name main.php inside /templates/layout folder. We usually create common sections of pages here inside it. We only render the dynamic content template wise into it.

To Add CSS

For adding CSS files we have several ways, but here we will use HTML helper and it’s method. Once we use this css() method it will look specified filename into path /webroot/css folder.

<?= $this->Html->css($filename) ?>

To Add JS

For adding Js files again we have several ways, but here we will use HTML helper and it’s method. Once we use this script() method it will look specified filename into path /webroot/js folder.

<?= $this->Html->script($filename) ?>

Render Flash Message

Suppose we need to display our flash messages into application. The best option is to give a fixed position to display it. Either flash message will be an error or success message.

To render flash message we use –

<?= $this->Flash->render() ?>

Render Template Contents

To display template contents with parent / master layout we have a special function that we use with a keyword.

We call fetch() method –

<?= $this->fetch("content") ?>

Let’s combine these all stuffs to main layout here inside main.php

<html>

<head>
    <title><?= $this->fetch("title"); ?></title>
    <!-- CSS Links -->
    <?php echo $this->Html->css("bootstrap.min.css"); ?>
    <?php echo $this->Html->css("jquery.dataTables.min.css"); ?>
</head>

<body>

    <div class="container">
       <h3 style="text-align: center;">This is Parent Layout</h3>
       <?= $this->Flash->render() ?>
       <?= $this->fetch("content") ?>
    </div>

    <!-- JS File -->
    <?php echo $this->Html->script("jquery.min.js"); ?>
    <?php echo $this->Html->script("jquery.validate.min.js"); ?>
    <?php echo $this->Html->script("custom.js"); ?>
</body>

</html>

Create Controller & Set Layout

Open project into terminal and run bake console command.

$ bin/cake bake controller Site --no-actions

It will create a file SiteController.php inside /src/Controller folder.

<?php

declare(strict_types=1);

namespace App\Controller;

class SiteController extends AppController
{
    public function initialize(): void
    {
        parent::initialize();
        $this->viewBuilder()->setLayout("main"); // Loading layout
    }

    public function index()
    {
    	$this->set("title", "Welcome Page")
    }
}

Create Template

Create a folder Site inside /templates folder. Create a file index.php inside /templates/Site folder.

Open index.php and write this code into it.

<?php 
  if(isset($title) && !empty($title)){
      $this->assign("title", $title);
  }
?>

This is a index page.
  

Create Route

Open routes.php from /config folder and add this route into it.

$routes->scope('/', function (RouteBuilder $builder) {

        // ...
        
        $builder->connect("/welcome", ["controller" => "Site", "action" => "index"]);
});

Application Testing

Start development server –

$ bin/cake server

URL: http://localhost:8765/welcome

Source code for template file when application compiled –

<html>

<head>
    <title>Welcome Page</title>
    <!-- CSS Links -->
    <link rel="stylesheet" href="/css/bootstrap.min.css"/>    
    <link rel="stylesheet" href="/css/jquery.dataTables.min.css"/> 
</head>

<body>

    <div class="container">
       <h3 style="text-align: center;">This is Parent Layout</h3>
       This is a index page.
   </div>

    <!-- JS File -->
    <script src="/js/jquery.min.js"></script>     
    <script src="/js/jquery.dataTables.min.js"></script>  
    <script src="/js/custom.js"></script></body>

</html>

We hope this article helped you to learn about CakePHP 4 How To Create Custom Layout Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.