I started with cakePHP a few months ago and was impressed by their documentation. I could find answers to most of my questions fairly quickly. However, I couldn't find a good tutorial on adding a site-wide template. Hopefully this will help other people with the same problem.
First start with an HTML template. If you don't feel like making one from scratch, any div layout will work fine. Open Source Web Design (http://oswd.org) has tons of free templates that work perfectly with CakePHP. Here's a simplified version of one of their templates:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <link rel='stylesheet' href='style.css'/> <title>CakePHP</title> </head> <body> <div class="site_container"> <div class="main_content"> <div class="top_header"> <div class="site_title"> <h1>CakePHP</h1> </div> </div> <div class="content"> <!-- Main Site Content --> </div> <div class="sidenav"> <h1>Navigation</h1> <a href='#'>Link 1</a> <a href='#'>Link 2</a> </div> </div> </div> </body> </html>
Copy this template to app/views/layouts/default.ctp. If that file doesn't exist, create it.
The first thing we have to change is the stylesheet. We are currently including the stylesheet with:
<link rel='stylesheet' href='style.css'/>
We need to copy the file style.css to app/webroot/css/style.css. Then replace the above code with:
<?php echo $html->css('style'); ?>
The next step is to include the page content. Edit the template as follows:
<!-- Main Site Content --> <?php $session->flash(); echo $content_for_layout; ?>
$session->flash(); prints error messages and alerts.
echo $content_for_layout; prints the page content.
Now for the side navigation. To keep the code clean, let's create a new file that just holds the navigation bar. Create the file app/views/elements/menus/sidenav.ctp. Here's some sample data for that page.
<?php echo $html->link("Home","/pages/home"); echo $html->link("About Us","/pages/about"); //if user is logged in if($this->Session->check('User')) echo $html->link("Sign Out","/users/logout"); else echo $html->link("Sign In","/users/login"); ?>
Here is the current code for the side navigation bar:
<div class="sidenav"> <h1>Navigation</h1> <a href='#'>Link 1</a> <a href='#'>Link 2</a> </div>
Change this to:
<div class="sidenav"> <h1>Navigation</h1> <?php echo $this->renderElement('menus/sidenav'); ?> </div>
You can add other page elements the same way you did the side navigation bar.
Hopefully this gives you an idea of how templates work in CakePHP.