One of the great aspects of Smarty is its high speed for a template engine. Smarty achieves its high speed by reading the template files once and generating new PHP scripts from those. The new generated PHP files can then directly be parsed by the PHP engine, where the resulting speed is almost as high as writing native PHP.
Using that pre-parsing technique, the time-consuming task of parsing templates for every request doe not happen.

Using the generated (temporarily) PHP scripts one can benefit from Smartys compiler-caching solutions. If required Smarty can even cache the resulting HTMl output. That results in the webserver practically sending a static HTML page, without the overhead of executing PHP calls and database queries.

Working mechanism

How do templates work?

Assume we are going to show data from within PHP. Without splitting PHP and HTML the code could look like that:

  <tr> <td>Name: <?php echo htmlspecialchars($name); ?></td> </tr>

Using Smarty we are able to split PHP and HTML, by using placeholder in the HTML code, which will than be filled by Smarty using the PHP backend.

The above example using Smarty would look like that:


// Create Smarty-Object
$template = new Smarty();
// fill placeholder with value
$template->assign('name', $name);
// HTML-Output


    <td>Name: {$name}</td>

Already with this small example you can see, that Smarty enhances the clarity of your code. You can concentrate on the real PHP code in your application, which is now not mixed-up within the HTML any longer.
Other way round, a webdesigner can work better on his HTML template, because he doesn't want to handle surrounding PHP code but concentrate on clean and good HTML code.

Further functionality

In real life we need more options when we are going to split HTML from PHP completely. Thats why Smarty gives us a lot of useful functions (german) to handle complex data like objects. But where Smarty is really good is in handling and displaying PHP arrays.

Smarty has also a well documented PlugIn-Interface and several options for a developer to extend it with modifier, filter, resources and block functions.

Example: Code for a formatted output of the Array $items (the function nl2br replaces line breaks with the html equivalent <br />):

  {foreach from=$items item="test"}

Part 1 vs. Part 2

This was the first of two parts introducing the Smarty template engine for the BIGACE Web CMS. The next part of our Smarty template engine introduction covers the points Speed, Advantages, Criticism, Links.

There is a previous posting about Smarty templates for your website and you can find even more Smarty designs in the extension wiki.