Reader's request: Understanding PHP4 's template concept
Now most of the template classes are provided with the block function, block is used to deal with an indeterminate number of HTML elements, when there are multiple layers of immutable elements, will use the block nesting, for the use of block nesting, after many tests or need to pay attention to the place, Here is an example of how block nesting is handled.
1, we first look at the example to achieve the effect (figure I):
2. template file test.htm
Template file is a static page, you can use your favorite page editor to develop his appearance
Untitled Document
| {myname} Test block |
| My implant garden: |
| {Animal} |
| {Plant} |
3, below is the PHP code file test.php
Include_once ("Template.inc");
$t = new Template (".");
$myname = "piglet chatter";
/***************************************
The animal array is used as the first block of cyclic data,
The plant array is used as the second-level block for cyclic data,
You can also read from the database according to your needs.
Data logging
***************************************/
$animal = Array ("Animal", "plant");
$plant = Array ("Piglet", "small white", "Xiao Qiang"), Array ("Rose", "Sunflower"));
$t->set_file ("Myfilehandle", "test.htm");
{myname} in template replaced by $myname value
$t->set_var ("MyName", $myname);
/*************************************
Set block, first set block, file sentence
The handle is Myfilehandle, then the second block is set,
The file handle is the first block. Note two sentences
The order
*************************************/
$t->set_block ("Myfilehandle", "Animallist", "a");
$t->set_block ("Animallist", "Plantlist", "P");
The first block starts.
for ($i =0; $i
/*******************************
This sentence, very important, can not be less, it's made
To clear the contents of the last second block.
Otherwise, the result, as shown in (Figure II), is
Displays the contents of the last second block.
The reason is because parse ("P", "Plantlist", True)
Selected items Ture
******************************/
$t->set_var ("P");
Replace {animal} in template with value of $animal[$i]
$t->set_var ("Animal", $animal [$i]);
The second block begins.
for ($j =0; $j
{Plant} in the template is replaced by the value of $plant[$i] [$j]
$t->set_var ("Plant", $plant [$i] [$j]);
Parse the first layer block
$t->parse ("P", "Plantlist", true);
}
Parsing the second tier block
$t->parse ("A", "animallist", true);
}
$t->parse ("Out", "Myfilehandle");
$t->p ("Out");
?>
4. The effect of missing $set_var ("P") statement:
The example is relatively simple, I have to be aware of the place in the corresponding location of the program has been explained. This is just one of the ways to deal with nested blocks, to share with you, and hope to help you. Thanks to PHPX and phpe.net for helping to complete this article.