Reusing controller views in CakePHP

CakePHP makes it easy to reuse your small blocks of presentation code throughout your application by using Elements. You can read more about them here:

http://book.cakephp.org/view/97/Elements

Sometimes though you want to reuse a regular controller view without moving the code to an element. In fact, if the view code is specific to the controller, it is good practice to keep it in the controller view.

Fortunately this is fairly simple. Just create the view and then reference it like this:

<?php echo $this->element('../projects/menu'); ?>

In the example above, I’m accessing the following file: /views/projects/menu.ctp

As always, the element will have access to all existing view variables (the ones typically passed using $this->set()).

Submit a Comment