Tutorials | PHP Template Files
This is a technique which I adopted upon completion of my own site using Smarty where I read an interesting article on why this was not always the best method of separating presentation from your scripts. Unfortunately I have long since lost the whereabouts of this article.
I'm sure there are occasions where using a template engine might be a good option but to my experience I prefer to simply use separate HTML with embeded PHP templates which only outputs values, loops through pre-defined, etc. I find this technique advantageous for the following reasons:
- No need to learn a new language syntax as when using Smarty or XSL. The tutorial will demonstrate how using PHP we can also neatly embed this into our HTML
- Smarty, it would appear, uses some clever caching to compensate for the fact that it is first having to be interpreted using PHP before it can be parsed. The caching system will make up for this but why not use the technique in this tutorial and if implementing a caching system it will even further enhance performance and not just compensate for additional overhead.
- The PHP syntax used here will work well in WYSIWYG editors – try loading a Smarty template into one of these and its not a pretty site. It is also a very similar look to XSL by using a tag like format.
- I can use PHP functions and object methods to further enhance the capabilities of the template. Both Smarty and XSLT fall short here.
Below I have created a simply example of a script that would include a PHP template. I'm not going to explain exactly what is happening here but just take for granted that the value returned to $arCars is an array of Car objects:
require_once('class.CarManager.php');
$arCars = $CarManager::GetCars();
// now we include the template
include('template.cars.php');
exit;
Now lets look at the template.cars.php file:
<html> <head> <title>List all cars</title> </head> <body> <p>We have a total of <?php echo count($arCars); ?> cars</p> <table> <tr> <th>Make</th> <th>Model</th> </tr> <?php foreach($arCars as $Car): ?> <tr> <td><?php echo $Car->GetMake(); ?></td> <td><?php echo $Car->GetModel(); ?></td> </tr> <?php endforeach; ?> </table> </body> </html>
Here were not generating any HTML from PHP and all the values we do output are done so neatly and presentation has been removed from the PHP scripting. Regardless of what means of presentation you use, your still going to have to use some form of code to loop through results whether it be XSLT or Smarty.

