- CakePHP - Discussion
- CakePHP - Useful Resources
- CakePHP - Quick Guide
- CakePHP - File upload
- CakePHP - Date and Time
- CakePHP - Pagination
- CakePHP - Creating Validators
- CakePHP - Validation
- CakePHP - Security
- CakePHP - Cookie Management
- CakePHP - Session Management
- CakePHP - Internationalization
- CakePHP - Form Handling
- CakePHP - Logging
- CakePHP - Errors & Exception Handling
- CakePHP - Services
- CakePHP - Delete a Record
- CakePHP - Update a Record
- CakePHP - View a Record
- CakePHP - Working with Database
- CakePHP - View Events
- CakePHP - View Elements
- CakePHP - Extending Views
- CakePHP - Views
- CakePHP - Controllers
- CakePHP - Routing
- CakePHP - Project Configuration
- CakePHP - Folder Structure
- CakePHP - Installation
- CakePHP - Overview
- CakePHP - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
CakePHP - Extending Views
Many times, while making web pages, we want to repeat certain part of pages in other pages. CakePHP has such facipty 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 CakeHttpMiddlewareCsrfProtectionMiddleware; use CakeRoutingRouteDashedRoute; use CakeRoutingRouteBuilder; $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(); });
Create an ExtendsController.php file at src/Controller/ExtendsController.php. Copy the following code in the controller file.
src/Controller/ExtendsController.php
<?php namespace AppController; use AppControllerAppController; class ExtendsController extends AppController{ pubpc function index(){ } } ?>
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
<span apgn="center"> <h1>Common Header</h1> </span> <?= $this->fetch( content ) ?>
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.
Execute the above example by visiting the following URL http://localhost/cakephp4/extend
Output
Upon execution, you will receive the following output.
Advertisements