Appending Template Text
There is also a third parameter that you can pass to
want to append data to the template variable rather than overwrite it. Simply
call
parse()
and pparse()
if youwant to append data to the template variable rather than overwrite it. Simply
call
parse()
or pparse()
with the third parameter as true, such as:
<?php
$t->parse("MyOutput","MyFileHandle", true);
?>
If MyOutput already contains data, MyFileHandle will be parsed and appended
onto the existing data in MyOutput. This technique is useful if you have a
template where you want the same text to be repeated multiple times, such as
listing multiple rows of results from a database query. You could also
display the variables in an array, such as in this example:
onto the existing data in MyOutput. This technique is useful if you have a
template where you want the same text to be repeated multiple times, such as
listing multiple rows of results from a database query. You could also
display the variables in an array, such as in this example:
<?php
$t
= new Template("/home/mydir/mytemplates/");
$t->set_file(array(
"mainpage" => "mainpage.ihtml",
"each_element" => "each_element.ihtml"));
reset($myArray);
while (list(
$elementName, $elementValue) = each($myArray)) {
// Set 'value' and 'name' to each element's value and name:
$t->set_var("name",$elementName);
$t->set_var("value",$elementValue);
// Append copies of each_element:
$t->parse("array_elements","each_element",true);
}
$t->pparse("output","mainpage");
?>
This example uses two templates, mainpage.ihtml and each_element.ihtml. The
mainpage.ihtml template could look something like this:
mainpage.ihtml template could look something like this:
<HTML>
Here is the array:
<TABLE>
{array_elements}
</TABLE>
</HTML>
The
which is repeated for each element of the array
template might look like this:
{array_elements}
tag above will be replaced with copies of each_element.ihtml,which is repeated for each element of the array
($myArray)
. The each_element.ihtmltemplate might look like this:
<TR>
<TD>{name}: {value}</TD>
</TR>
The result is a nicely formatted table of the elements of
it be nice if these two templates could be combined into one template file? In
fact, they can be combined using template blocks. Template blocks let you extract a
block of text from a template so you can repeat it multiple times, or do anything
else you would like with it. But I’ll save that feature for another article.
$myArray
. But wouldn’tit be nice if these two templates could be combined into one template file? In
fact, they can be combined using template blocks. Template blocks let you extract a
block of text from a template so you can repeat it multiple times, or do anything
else you would like with it. But I’ll save that feature for another article.