Home Web Design Computing Music

DLib Library

The examples on the previous page use a mixture of tables and direct printing. Normally, the table commands such as pTable, tRow and endTable output the HTML they generate directly via the PHP print command so this is no problem. However, the library also provides an alternative method of HTML page creation which lends itself better to templates. This is a class called HtmlPage.

An HtmlPage object can "plug" items into the template either into named locations or into the general "content" area. Here is an example:

$tpl = <<<ENDTPL
<div id="screen">
  <div id="logo">__LOGO__</div>
  <div id="menu">__MENU__</div>
  <div id="content">__CONTENT__</div>
  <div id="copyright">__COPYRIGHT__</div>

$hpg = new HtmlPage (array ("charset" => "ISO-8859-1", "title" => "A Better Web Site"));

$hpg->setTemplate ($tpl);
$hpg->addStyleSheet ("/css/style.css");
$hpg->addJavaScript ("/js/menuhandler.js");

$hpg->replace ("__COPYRIGHT__", "Copyright " . date ("Y") . 
  " by the Very Big Corporation of America"));
$hpg->replace ("__MENU__", getMenu ());
$hpg->add (h1 ("The Main Title"));
$hpg->addPara ("A paragraph of information.");

$hpg->output ();

function getMenu ()
  // Code to generate an on-screen menu...

The above example is doing the following:

  • A template is defined as $tpl.
  • An HtmlPage object is initialised as $hpg.
  • The template is added to $hpg.
  • CSS Style sheets and JavaScript are added. Any number of these can be added - additionally, there are optional HPJSF_xxx flags which dictate where on the page the JavaScript is added and whether or not the first parameter is a file to import or if it is code.
  • Named parts of the template are filled in. There are two methods of doing this: the first, using the replace method, will substitute the entire section with the supplied data; the second, using the add method, will add the supplied data to anything previously added to that section. The add method either adds to the named section or to the default "CONTENT" section if only the data is supplied. The addPara method is a specialised version of add which wraps <p> tags around the supplied data.
  • Finally, the page is sent to the browser via the output method.

The use of common templates with HtmlPage mean that all pages on a site that use the same template can be updated at once by altering the template.