View Elements

Certain parts of the web pages are repeated on multiple web pages, but at different locations. CakePHP can help us reuse these repeated parts. These reusable parts are called Elements – help box, extra menu, etc. An element is basically a mini-view. We can also pass variables in elements.

Cake\View\View::element(string $elementPath, array $data, array $options =[]

There are three arguments to the above function as follows −

  • The first argument is the name of the template file in the /src/Template/element/ folder.
  • The second argument is the array of data to be made available to the rendered view.
  • The third argument is for the array of options. e.g. cache.

Out of the 3 arguments, the first one is compulsory, while the rest are optional.

Example

Create an element file at src/Template/element directory called helloworld.php. Copy the following code in that file.

src/Template/element/helloworld.php

<p>Hello World</p>

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

src/Template/Elems/index.php

Element Example: <?php echo $this->element('helloworld'); ?>

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('/element-example',['controller'=>'Elems','action'=>'index']);
   $builder->fallbacks();
});

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

src/Controller/ElemsController.php

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

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

Output

Upon execution, the above URL will give you the following output.

Element Example

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *