Sample Code - Using PHP to Create a Web Site TemplateLet's say you wanted to create a reusable web site template that looks like this using PHP:
To create a reusable web site layout using PHP, you will first need to create a template.html file that has the reusable parts of your site (in this case, banner + navigation bar). Then, you use PHP to define some variables that hold the parts of the page that you want to change (in this case, title and content area). Finally, for all of your content pages, you add 4 lines of PHP to attach the template to the page. You do this by first filling in the areas that the template left blank (title and content, in this case), then loading the template. The following sample code demonstrates this: template.html (or template.php, if you wish)<head>
<title><?php echo $TITLE; ?></title>
</head>
<body>
<div id="header">
<h1>My Website</h1>
</div>
<div id="navigation">
<p><a href="home.html>Home</a></p>
<p><a href="home.html>Home</a></p>
<p><a href="home.html>Home</a></p>
</div>
<div id="content">
<?php echo $CONTENT; ?>
</div>
</body>
home.html<?php $TITLE = "My Home Page"; ob_start(); ?> <p>Welcome to my web page<p> <?php $CONTENT = ob_get_clean(); include "template.html" ?> Explanation:In case you wish to understand the PHP code of home.html in detail: the key is to understand the "ob_start()" command. This trick is called output buffering. After ob_start(), PHP will take everything you write outside of php (in this case, the site's contents) and store it in memory instead of writing it to the screen. You can then retrieve the site contents that PHP remembered by using ob_get_clean(), all without putting anything on the screen. I could have achieved the same effect by just storing the site contents in one large string variable named $CONTENT. But using output buffering is a much better solution, mainly because you will still be able to see all of your site in a visual editor like Dreamweaver or PHPEdit. Another trick used here is to exploit the way PHP handles included files. Notice that before the last line where I load the template ("include 'template.html'"), all I've done is fill in some variables. Nothing has been output to the screen yet. But when I include the template after I've filled in these variables, the template will show up on the screen with the contents I've already loaded in home.html, because the template was set up to output the variables I filled in in home.html. Back to site layout tutorial |
|||||