Template-Based Web Development With patTemplate (part 2) - Crash Bang Boom (
Page 13 of 14 )
Another
common use of patTemplate involves using it to display error and success codes
while processing a script. Consider the following templates, which set up error
and success pages respectively:
<!-- common.tmpl -->
<patTemplate:tmpl name="error">
<html>
<head><basefont face="Arial"></head>
<body>
An error occurred. Please contact the <a
href="mailto:webmaster@domain.com">webmaster</a>.
</body>
</html>
</patTemplate:tmpl>
<patTemplate:tmpl name="success">
<html>
<head><basefont face="Arial"></head>
<body>
The operation was successfully executed.
</body>
</html>
</patTemplate:tmpl>
Here's how I might use them in a script:
<?php
function checkErrors()
{
global $template, $error;
if ($error)
{
$template->displayParsedTemplate("error");
die;
}
}
function raiseError()
{
global $error;
$error = true;
}
// 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("common.tmpl");
// set error variable
$error = false;
// script starts here
// process section 1
// no errors
checkErrors();
// process section 2
// let's assume an error occurred
raiseError();
checkErrors();
// process section 3
// no errors
checkErrors();
// end of script processing
// if we get this far, it means no errors
// display success code $template->displayParsedTemplate("success");
?>
In this case, since an error was raised in section two of the
script, the checkErrors() function will kill the script and display the error
template when it is next invoked.
If, on the other hand, no errors are
raised during execution of the script, the final call to checkErrors() will have
no effect, the line following it will be executed and a success template will be
displayed.
This is a fairly primitive example, but it does serve to
demonstrate how a template engine can assist in creating powerful, flexible
error handlers for your Web applications. It works like a charm most of the time
- not to mention being fairly easy to maintain.