Building Whole Tables
September 22, 2000
I have also written a short example which demonstrates how to build
whole tables with single row templates. It is effective, because
you still do not need to tinker with HTML directly.
We attach the content of a template to an
already defined unique name to build the HTML table. This can be
done by sticking a single "." into the front of the template name
when calling $tpl->parse():
<?php
# assign the content of template foo to the unique name TPL1
$tpl->parse(TPL1, "foo");
# attach the content of template bar to the unique name TPL1
$tpl->parse(TPL1, ".bar");
?>
page.tpl
<HTML>
<HEAD><TITLE>Feature world - {PAGE_TITLE}</TITLE></HEAD>
<BODY BGCOLOR=BLACK TEXT=WHITE>
<H1>{PAGE_TITLE}</H1>
{PAGE_CONTENT}
</BODY>
</HTML>
table.tpl
<TABLE>
<TR> <TH>name</TH> <TH>size</TH> </TR>
{TABLE_ROWS}
</TABLE>
table_row.tpl
<TR>
<TD>{FILENAME}</TD>
<TD>{FILESIZE}</TD>
</TR>
yad.php3
<?php
include "class.FastTemplate.php3";
function InitializeTemplates() {
global $tpl;
$tpl = new FastTemplate(".");
$tpl->define( array( page => "page.tpl",
table => "table.tpl",
table_row => "table_row.tpl" ) );
}
function ReadCurrentDirectory() {
global $tpl;
$handle = opendir(".");
while($filename = readdir($handle)) {
$tpl->assign(FILENAME, $filename);
$tpl->assign(FILESIZE, filesize($filename));
$tpl->parse(TABLE_ROWS, ".table_row");
}
closedir($handle);
$tpl->parse(PAGE_CONTENT, "table");
}
function PrintPage($title) {
global $tpl;
$tpl->assign(PAGE_TITLE, $title);
$tpl->parse(FINAL, "page");
$tpl->FastPrint(FINAL);
}
InitializeTemplates();
ReadCurrentDirectory();
Printpage("Yet Another Demo");
?>
Speed discussion
"Ok," you might say, "that is all fine and nifty. But doesn't it impact
the speed of my web site?"
Yes, your site will probably become faster. There is a simple reason
for that: Because you as the coder are focused on designing your
application and building code, your code will be more efficient, handling
the same task easier and quicker. So, you might add just another reason
to the above list why you should consider using FastTemplate in your
next PHP project.
If you just want to convert an existing web site, the performance hit
will probably not be noticed. I introduced a regex (short for
"regular expression") cache into PHP 3.0.7 which helps in this special case.
Because FastTemplate uses a regex for every macro, each regex will be
compiled only once and the speed impact becomes negligible.
Additional Resources:
PHP Resources
FastTemplate Substitution
Templates - why and how to use them in PHP3
|