HomePHP Page 5 - Template-Based Web Development With patTemplate (part 1)
Music To Your Ears - PHP
Most PHP-based Web sites are a mush of intermingled HTMLmarkupand PHP function calls, making them hard to decipher and maintain. Butthere *is* a simpler way - using templates to separate layout frombusinesslogic. This article shows you how.
While on the subject, it's important to note that it isn't even necessary for all your templates to be stored in one physical file - patTemplate allows you the flexibility to store your templates in as many physical containers as you like, and to organize them in the manner that best suits your project. The template engine comes with a fairly well-developed API to read and combine the templates in the different files together - as the following example demonstrates:
<!-- common page elements -->
<!-- stored in file common.tmpl -->
<!-- page header -->
<patTemplate:tmpl name="header">
<html>
<head>
<basefont face="Arial">
</head>
<body bgcolor="navy" text="white" link="white" vlink="white"
alink="white">
</patTemplate:tmpl>
<!-- page footer -->
<patTemplate:tmpl name="footer">
<p> <p align="right">
<font size="-2">{COPYRIGHT}</font>
</body>
</html>
</patTemplate:tmpl>
<!-- page body -->
<!-- stored in file music.tmpl -->
<patTemplate:tmpl name="body">
<center>
Feelin' blue? How about a little <a
href="http://www.melonfire.com/community/columns/boombox/">music</a>?
</center>
</patTemplate:tmpl>
<!-- main page -->
<!-- stored in file main.tmpl -->
<patTemplate:tmpl name="main">
<patTemplate:link src="header" />
<patTemplate:link src="body" />
<patTemplate:link src="footer" />
</patTemplate:tmpl>
Here's the script which puts them all together:
<?php
// include the class
include("include/patTemplate.php");
// initialize an object of the class
$template = new patTemplate();
// set template location
$template->setBasedir("templates");
// add templates to the template engine
$template->readTemplatesFromFile("music.tmpl");
$template->readTemplatesFromFile("common.tmpl");
$template->readTemplatesFromFile("main.tmpl");
// assign values to template variables
$template->AddVar("footer", "COPYRIGHT", "This material copyright
Melonfire, " . date("Y", mktime()));
// parse and display the template
$template->displayParsedTemplate("main");
?>