OntoSys  

PHP Templates

This note describes a PHP templating scheme where
  1. Each template file contains a full HTML document, so that a designer can edit the template file in a WYSIWYG tool like Dreamweaver. There is no need to store fragments of the HTML template out of context in separate files.
  2. Content files are primarily HTML with small embedded PHP scripts. There is no need to put large chunks of HTML content in PHP strings, such as assigning to a 'content' template variable.
We use the Template class provided in the template.inc file shipped with PHPlib.

Example files

page.ihtml -- A template file

<!-- BEGIN header -->
<html>
<head>
<title>{TITLE}</title>
</head>
<body>
<h1>{TITLE}</h1>
<hr>
<!-- END header -->

{CONTENT}

<!-- BEGIN footer -->
<hr>
<address>foo@bar.com</address>
<!-- END footer -->

The first BEGIN and END comment lines define a block named header, and the second such lines delimit a similar footer block. The template has variables for TITLE and CONTENT.

Our example will use the blocks, not the file as a whole, so the CONTENT variable part will be unused since it is outside of any block. In fact, it might be useful to put some representative text (Lorem ipsum...) in that place so that the page-layout designer sees how that section will be formatted.

example1.php3 -- A content file using the template

<?php
include("template.inc");
$t = new Template(".", "keep");
$t->set_file('page', "page.ihtml");
$t->set_var('TITLE', "An Example Generated File");

$t->set_block('page', 'header');
// The 'header' block has been extracted from the 'page' template and
// saved as a template variable also named 'header'.
$t->pparse('out', 'header');
// header has been output.
?>

<h3>Arbitrary HTML and PHP content here</h3>
yada, yada, yada
... lots more HTML content goes here ...

<?
$t->set_block('page', 'footer');
$t->pparse('out', 'footer');
// footer has been output
?>

This typical content file loads a page template variable with the entire contents of the template file, then (the key point of this note) it calls set_block() to extract the header block from the page template and save it as the header template variable. Note that page is never output as a whole -- it is only a source for extracting the header and footer blocks.

Here is a link to example.php3 where you can see the resulting page.

I typically write some helper functions to wrap the pairs of set_block and pparse function calls.


OntoSys, Inc. - 38W242 Deerpath Rd - Batavia, IL 60510
phone +1.630.879.1312 - fax +1.630.879.1370
email info@ontosys.com - www.ontosys.com
Last modified: 1970-01-01 00:00 Z.
Copyright © 1999 - 2004 by Fred Yankowski.
All rights reserved.