HomePHP Page 4 - Template-Based Web Development With patTemplate (part 2)
Looping The Loop - PHP
Got the basics down? Well, here's the advanced course - thisarticle demonstrates some of patTemplate's more sophisticated features,including the ability to dynamically show or hide templates, inheritvariables, use loops and conditional branches, and create dynamic,template-based forms and error handlers.
You can force a particular template to loop a specific number of times by adding the "loop" attribute to it. Here's an example:
<patTemplate:tmpl name="main" loop="12">
It is now 1 o'clock
</patTemplate:tmpl>
Here's the script that powers it:
<?php
// include the class
include("include/patTemplate.php");
// initialize an object of the class
$template = new patTemplate();
// set template location
$template->setBasedir("templates");
// add templates to the template engine
$template->readTemplatesFromFile("loop.tmpl");
// parse and display the template
$template->displayParsedTemplate("main");
?>
And here's the output:
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
It is now 1 o'clock
Fairly simple, and useful when all you need to do is display
a piece of text or markup a specified number of times (you can use the setAttribute() method, discussed a little later, to set the loop counter dynamically). And you can make it even more useful by incorporating the current value of the loop counter within your template - like I've done below, with the special {PAT_ROW_VAR} variable:
<patTemplate:tmpl name="main" loop="12">
It is now {PAT_ROW_VAR} o'clock
</patTemplate:tmpl>
In this case, the same PHP script will generate slightly
different output:
It is now 1 o'clock
It is now 2 o'clock
It is now 3 o'clock
It is now 4 o'clock
It is now 5 o'clock
It is now 6 o'clock
It is now 7 o'clock
It is now 8 o'clock
It is now 9 o'clock
It is now 10 o'clock
It is now 11 o'clock
It is now 12 o'clock