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:

[code=php]
element(‘../projects/menu’); ?>
[/code]

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()).

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.