HomePHP Page 6 - Web Development With PHP FastTemplate
Flavour Of The Month - PHP
Typically, most PHP-based Web sites use scripts which containintermingled PHP and HTML code. While this speeds up development, it alsohas a downside: an interface designer cannot modify page layouts or HTMLtemplates without the assistance of an experienced PHP developer. Well,there's a solution to the problem - and you'll be surprised to hear thatit's been around for quite a while. Say hello to PHP FastTemplate.
Another useful FastTemplate feature involves creating a sequence of items by appending to a single variable; this comes in particularly handy when creating HTML constructs like lists and table rows. Consider the following templates:
In this case, I plan to build a list (from a database) by repeatedly
calling the "list_item.tpl" template; this list will then be assigned to a FastTemplate variable named "LISTCONTENT", and substituted in the main page, "list.tpl". Here's the script:
<?
// list.php - item list
// include class file
include("class.FastTemplate.php3");
// instantiate new object
$obj = new FastTemplate("./tmpl/");
// assign names for template files
$obj->define(array(
"list" => "list.tpl",
"list_item" => "list_item.tpl"
));
// get item list
/*
// open connection to database
$connection = mysql_connect($hostname, $user, $pass) or die ("Unable to
connect!");
// query
$query = "SELECT item from itemtable";
$result = mysql_db_query($database, $query, $connection);
// build $items array
$items = array();
while(list($item) = mysql_fetch_row($result))
{
$items[$count] = $item;
$count++;
}
*/
// assume it looks like this..
$items = array("vanilla", "pineapple", "strawberry", "chocolate chip",
"peach", "banana", "grape");
// build LISTCONTENT variable by concatenation of multiple instances of
"list_item" template
for ($x=0; $x<sizeof($items); $x++)
{
$obj->assign("ITEM", $items[$x]);
// append the result of parsing the template to LISTCONTENT
$obj->parse(LISTCONTENT, ".list_item");
}
// parse templates
$obj->parse(RESULT, "list");
// and print
$obj->FastPrint(RESULT);
?>
Each time the loop iterates through the $items array, a new value is
assigned to the "ITEM" variable. FastTemplate then parses the "list_item" template and replaces the placeholder with its actual value. The "." operator is used to append the result of each iteration to the "LISTCONTENT" variable.
This technique comes in very handy when building repetitive sequences - all you need to do is build a template containing one item of the sequence, and let FastTemplate generate as many copies of it as you need.