This tutorial shows how you can attach dynamic menu or any content to layout that you still want to call from controllers.
Making dynamic menus for layouts is not as to get hang on, but if you learn it then it seems logical and simple enough. Here are steps per files.
Model:
You need a simple model for this tutorial. I have my menu names in database so I will call those from there. Table name is "menus" and menu names are in column named "menu". Here is the code for my model:Source code viewer
<?php class Menu extends AppModel { var $name = 'Menu'; } ?>Programming Language: PHP
Controller:
Controller returns array of menus to who ever is requesting this controller. Controller is in controllers folder and the name is menus_controller.php.Source code viewer
<?php class MenusController extends AppController { var $name = 'Menus'; function index() { $menus = $this->paginate(); return $menus; } } ?>Programming Language: PHP
Elements:
In views folder there is elements folder. This element goes in there. I called it to menu.ctp, contents of this file:Source code viewer
<?php //$menus equals with array of variables from database. You can give all sorts of parameters. $menus = $this->requestAction('menus/index/sort:menu/direction:asc'); foreach ($menus as $menu) { echo '<h2>'.$menu['Menu']['menu'].'</h2>'; } ?>Programming Language: PHP
Layout:
Here is one really basic layout. And we get the element to div thats id is "menu".Source code viewer
<?php echo $html->docType('xhtml-trans'); ?> <div id="header"> Title<br /> Slogan </div> <div id="layout"> <div id="menu"> <?php echo $this->element('menu'); ?> </div> <div id="content"> <?php echo $content_for_layout; ?> </div> </div> <div id="footer"> Copyright © 2010 example.com - All Rights Reserved </div>Programming Language: HTML
And that's it. Dynamic content to layouts in CakePHP. You can make any dynamic data not just menus and it's not necessary to pull the menus from database as well. Though if it's static then there is no reason to include any controller. I saw one guy make the same thing using sessions and I thought that can't be right. Use sessions for holding content, so I thought that I need to write this tutorial.