CakePHP - 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 −

  • 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.


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


<p>Hello World</p>

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


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

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


   use Cake\Core\Plugin;
   use Cake\Routing\RouteBuilder;
   use Cake\Routing\Router;

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

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


   namespace App\Controller;
   use App\Controller\AppController; 
   use Cake\ORM\TableRegistry;
   use Cake\Datasource\ConnectionManager;

   class ElemsController extends AppController{
      public function index(){

Execute the above example by visiting the following URL.



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

View Elements