Web Development With PHP FastTemplate - Flavour Of The Month
(Page 6 of 9 )
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:
<!-- begin: list.tpl -->
<html>
<head>
</head>
<body>
<ul>
{LISTCONTENT}
</ul>
</body>
</html>
<!-- end: list.tpl -->
<!-- begin: list_item.tpl -->
<li>{ITEM}
<!-- end: list_item.tpl -->
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.

Next: A Strict() Master >>
More PHP Articles
More By icarus, (c) Melonfire