Parsing
By now you are at least somewhat familiar with the
parse() method. In the following examples the parse
method will be explained in more detail.
The parse() Method
The parse() method, simply put, is used to parse blocks within
your current template object. Earlier we discussed block syntax and
block hierarchy. We know all about the main block
and sub blocks. Going forward, we'll concentrate on complex block
structures and controlling those structures with parse().
Consider the following example:
- <?php
- /*include the class*/
- include_once('../class.XiTemplate.php');
-
- /*instantiate the class and pass the path to your HTML template file*/
- $xitpl = new XiTemplate('templates/example.tpl');
-
- /*let's make dynamically make a table*/
- $rows = 3;
- $cols = 4;
-
- for ($i = 0; $i < $rows; $i++) /*loop to make the tr's*/
- {
- for ($x = 0; $x < $cols; $x++) /*loop to make the td's*/
- {
- $xitpl->assign('VARIABLE', 'row: '.($i+1).', column: '.($x+1));
- /*notice the hierarchy by which blocks must be parsed...*/
- $xitpl->parse('main.tr.td');
- }
- /*...always parse child blocks first*/
- $xitpl->parse('main.tr');
- }
-
- /*parse the "main" block of the template (the whole page)*/
- $xitpl->parse('main');
-
- /*send the final page out to the browser*/
- $xitpl->out('main');
- ?>
Here is a sample template to work with the above PHP
script:
<!-- BEGIN: main -->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>XiTemplate</title>
</head>
<body>
<h1>XiTemplate</h1>
<p>Here is a table made up of several sub blocks</p>
<table border="1" cellpadding="2" cellspacing="0">
<!-- BEGIN: tr -->
<tr>
<!-- BEGIN: td -->
<td>{VARIABLE}</td>
<!-- END: td -->
</tr>
<!-- END: tr -->
</table>
</body>
</html>
<!-- END: main -->
In the above example there are three blocks: 1) the main block,
which constitutes the entire page, 2) a block named "tr", and 3) a block
named "td".
There are a few important things to take note of when dealing with
multiple blocks and nested blocks.
Nested child blocks must always be parsed before the parent
block they live in.
Child blocks must be terminated with an END tag before the
parent block is terminated. Similar to HTML, you would never close a
table tag before closing a table row.
Template variables (including $nullValue) must be assigned
prior to parsing the target block where the template variable
lives.
Blocks can be parsed over and over again as many times as you
need them to be. In the above example both "tr" and "td" are parsed
multiple times to create a complex table.
That about covers parse() in all its wonder.
Next in this tutorial is rparse(). Click "next" to learn
more.