All About Smarty – The PHP Template Engine

Smarty is a PHP template engine written by Monte Ohrt and Andrei Zmievski. Yet another template engine you say? The authors (and I too) would disagree. Smarty is different from the rest of the pack. What differentiates Smarty from other template engines like FastTemplate and patTemplate is that Smarty compiles your templates into PHP scripts, eliminating the overhead incurred in parsing the templates every time they’re accessed. This makes Smarty very scalable for large applications and high-traffic Websites …and if that didn’t make any sense to you, just take it that Smarty is very fast and would work well in stressful and high-traffic conditions!

The Smarty template engine has several other outstanding features besides template compilation, and we’ll discuss these a little later. But first, let’s de-mystify template compilation…

Template Compilation Explained

What does ‘compilation of templates’ mean, anyway? What do Web pages have to do with compiling? Isn’t compiling something C++ and Java programmers do? Yes – but this is a different sort of compilation.

Smarty parses your templates and creates PHP scripts from them (instead of binaries, as in general programming). Then, when your Web page is viewed, Smarty reads from these PHP scripts instead of pulling the templates themselves, which saves the work of having to parse your templates again. Smarty is smart about when to compile, too: it only re-compiles your templates when you make changes to them, so you don’t have to worry about manually compiling the templates (this is similar to JSP, if you’re aware of how it works).

The good thing about this is that you don’t even have to know the PHP scripts are there, nor how compiling works. It’s all hidden from view, so if you employ template designers to work on your templates, they (or you, if you design your own templates) don’t have to know that Smarty is a ‘compiling template engine’.

Caching

Smarty also features built-in caching of your template outputs. Smarty caches the output of the template contents, saving the overhead expense involved in retrieving your data from a data source. This data source would usually be external and slow, and is often the bottleneck in your application, like a remote database. Smarty caches the output of your template with this data from your data source, and saves you from having to connect to the database every time your Web page is accessed. If you have a slow-responding database server or are making multiple queries to your database, this caching feature would greatly improve the performance and responsiveness of your Web pages.

Of course, there are cases when you don’t actually want your template output to be cached, for instance, a stock ticker or situation where you constantly make changes to your database, which need to be immediately reflected on your Web pages. No problem! Smarty is again smart enough to allow you to specify what should or should not be cached.

In fact, you can have cached and un-cached portions on the same template page, as Smarty allows you to specify exactly what you don’t want cached (like that stock ticker at the bottom of the page) and what you do want cached (such as your navigation bar, which is seldom changed). You can also set the cache expiry time so that your template output is cached only for a specific length of time. You can thus achieve the middle-ground between having up-to-date dynamic content and quick-to-load Web pages.

One point to note (and which the authors of Smarty are quick to point out) is that this caching functionality is totally different from that of Zend Cache, PHP Accelerator and the like. Caching tools like PHP Accelerator cache the complied bytecode of your PHP scripts, whereas Smarty caches the output of your templates. As such, Smarty can work hand in hand with Zend Cache, where Zend Cache would cache the PHP scripts that Smarty creates from your templates. This makes for excellent performance, as evidenced by benchmarks. To quote the authors:

"Smarty’s performance _really_ excels in combination with a PHP accelerator."

Variable Modifiers

Smarty also provides variable modifiers, which, as the name implies, allow you to modify the contents of a variable. You can do things like uppercase a string (e.g.{$title|upper} which would convert your $title into all uppercase characters), truncate a string (e.g. {$content|truncate:30} which would allow you to display the first 30 characters of $content and follow that with ‘...‘, particularly useful for displaying email or forum topic previews) or even use regular expressions to search and replace a string (e.g.{$article|regex_replace:"/bad word/":"***"} which would replace all occurrences of ‘bad word‘ in $article with ‘***‘).

Variable modifiers give your template designers the ability to modify your template variables without being confused by those funny characters we programmers so like to use. This sanitized method of ‘programming’ gives your template designers greater control over the formatting of your template variable, though they would need to know the variable modifiers available to them. It is still, without doubt, a useful feature, as the syntax is kept simple and is accessible to even non-programmers.

Template Functions

Smarty provides built-in and custom functions for use in your templates. These functions are like the API of Smarty templates, except that custom functions can be modified but not built-in functions. Functions allow you to do things like program conditional output (using if statements), perform iteration with dynamic loops (using foreach or section), load config files, cycle though a set of values (useful for alternating table row colors), keep a counter (useful for numbering list data), and much more.

It’s particularly of use to those of us generating Web pages with content from databases are the looping functions (section and foreach), which you can use to loop over and display a result set.

Filters

Smarty allows you to specify (‘register‘ or ‘load‘ actually) filters through which you can run your templates before or after they are compiled. Prefilters are functions that your templates are run through before they’re compiled; postfilters after; and output filters, upon the template output as it is requested.

‘Why filters?’ you say. Prefilters allow you to do things like removing unwanted comments (such as those created by Dreamweaver) and ensuring content in the templates you don’t want does not go through to the compiler. Postfilters let you add additional information to your templates, such as the template creation date (as a comment) after they’re compiled. Output filters give you the ability to modify your template output, allowing you to do things like obfuscating email addresses on your Web page to protect against spambots (using a preg_replace()).

Config Files

Config files are configuration files where you can store global template variables. This allows you to store variables that should affect every template (i.e. global variables) in a central location. A good example of such a variable would be the color scheme for your templates. Your template designers only have to change the values in the config file should a color scheme revamp be required. This saves them suffering through the painful alternative of going through every individual template to change the colors.

Config files also allow for sections, which are not unlike those in .ini files. The section names are enclosed in brackets (e.g. [welcome_page]) and are only loaded upon request. Anything that’s not in a section is globally available (upon a call to the config_load function).

Plug-ins

The Smarty plug-in architecture was introduced in version 2.0 and allows you to customize Smarty to suit your purposes (however grand or nefarious). The prefilters, postfilters and output filters I discussed earlier are just some of the plug-in types available to the customizer. Other plug-in types are the modifier, block, compiler, resource and insert types.

With plug-ins, you can create your own template functions, variable modifiers and filters. You can even change the data source you want Smarty to read from (the default is from flat files), using a resource plug-in. With a resource plug-in, you can save your templates in a database, and retrieve them using sockets (or any other method you use to access templates with PHP. This means you can access just about any source).

Conclusion

Smarty is a quality template engine and one you should definitely consider, should you be on the lookout for a PHP version.

Combine Smarty’s template compilation and PHP’s inherent efficiency in generating Web pages, and you’ve got yourself a winner in the speed race. Smarty also offers extensive functionality, including template functions and variable modifiers, which can be extended using a well-designed plug-in architecture.

All that speed and functionality doesn’t come at the price of usability: the learning curve is no steeper than that of other template engines. Smarty is also supplemented with excellent documentation that’s available online and for download at the Smarty Website.

Andrei Zmievski, one of the authors, works on the PHP development team too, and he keeps Smarty’s development closely tied to that of PHP. So you can be confident that the latest changes to PHP (like the recent register_globals issue in PHP 4.2.0) will be supported by Smarty.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.