A PHP Template System

Now that you know the basics of how PHP works, let's look at a real world application. We'll use PHP to create a template system. You already got a sneek peek at what the template would look like in the introduction to this section. Here is the code again for the template:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
   <head>
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
     <title><?php echo $title; ?></title>
   </head>
   <body>
     <h1><?php echo $h1; ?></h1>
     <div id="content">
       <?php content(); ?>
     </div>
   </body>
 </html>

You would save this code in a file called template.php.

How do We Use the Template?

We still have to create separate files with the text content that goes in the web pages. In our system, we create some variables for the title and heading, and a function for the main content. Then, at the bottom of the document, we have to include our template so that the content has a place to go. A simple home page could look like this:

<?php
$title = 'Home';
$h1 = 'Home';

function content() { ?>
<p>Here is the content of my home page.</p>
<?php }

include 'template.php';
?>

It Won't Look Right Until You Upload it to the Web Server

When you open this file in Dreamweaver's design view, all you will see is the text from the content() function. Everything else is kept hidden, but you can see it all in the code view. Also, you won't be able to see what the page really looks like until the web server puts it all together on the server itself. This takes some getting used to. You won't be able to see the styles or the template at all. It will all look very bland. But once you upload it, the server finds all the component parts and reassembles them into a single web page, as if it was all one unit, even though it's actually broken up into several pieces.

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 2.5 License.