CakePHP Extending Views

WBOY
Release: 2024-09-10 17:25:28
Original
851 people have browsed it

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.

Example

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

config/routes.php

<?php
use Cake\Http\Middleware\CsrfProtectionMiddleware;
use Cake\Routing\Route\DashedRoute;
use Cake\Routing\RouteBuilder;
$routes->setRouteClass(DashedRoute::class);
$routes->scope('/', function (RouteBuilder $builder) {
   $builder->registerMiddleware('csrf', new CsrfProtectionMiddleware([
      'httpOnly' => true,
   ]));
   $builder->applyMiddleware('csrf');
   $builder->connect('extend',['controller'=>'Extends','action'=>'index']);
   $builder->fallbacks();
});
Copy after login

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

src/Controller/ExtendsController.php

<?php
   namespace App\Controller;
   use App\Controller\AppController;
   class ExtendsController extends AppController{
      public function index(){
      }
   }
?>
Copy after login

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

src/Template/Extends/header.php

<div align="center">
   <h1>Common Header</h1>
</div>
<?= $this->fetch('content') ?>
Copy after login

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

src/Template/Extends/index.php

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

Execute the above example by visiting the following URL http://localhost/cakephp4/extend

Output

Upon execution, you will receive the following output.

Common Header

The above is the detailed content of CakePHP Extending Views. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!