CakePHP – Extending Views

CakePHP – Extending Views

Many times, while making web pages, we want to repeat certain part of pages in other pages. CakePHP has such facility by which one can extend view in another view and for this, we need not repeat the code again. The extend() method is used to extend views in View file. This method takes one argument, i.e., the name of the view file with path. Don’t use extension .ctp while providing the name of the View file.


Make changes in the config/routes.php file as shown in the following program.


   use CakeCorePlugin;
   use CakeRoutingRouteBuilder;
   use CakeRoutingRouter;

   Router::scope('/', function (RouteBuilder $routes) {

Create a ExtendsController.php file at src/Controller/ExtendsController.php. Copy the following code in the controller file.


   namespace AppController;
   use AppControllerAppController;

   class ExtendsController extends AppController{
      public function index(){

Create a directory Extends at src/Template and under that folder create a View file called header.ctp. Copy the following code in that file.


<div align = "center"><h1>Common Header</h1></div>

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

Create another View under Extends directory called index.ctp. Copy the following code in that file. Here we are extending the above view header.ctp.


<?php $this->extend('header'); ?>
This is an example of extending view.

Execute the above example by visiting the following URL.



Upon execution, you will receive the following output.


Was this article helpful?

Related Articles

Leave A Comment?

You must be logged in to post a comment.