#native_company# #native_desc#
#native_cta#

Templates: The PHPLib Way Page 4

By David Orr
on July 30, 2000

Appending Template Text

There is also a third parameter that you can pass to parse() and pparse() if you
want 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:

<?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:

<HTML>

  Here is the array:

  <TABLE>

    {array_elements}

  </TABLE>

</HTML>


The {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.ihtml
template might look like this:

<TR>

  <TD>{name}: {value}</TD>

</TR>


The result is a nicely formatted table of the elements of $myArray. But wouldn’t
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.

1
|
2
|
3
|
4