All About Smarty – The PHP Template Engine

    Cheah Chu Yeow
    Cheah Chu Yeow
    Share

    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.

    Frequently Asked Questions about Smarty PHP Template Engine

    What is the Smarty PHP Template Engine?

    Smarty is a PHP-based template engine that separates the application logic from the presentation layer of your web application. It provides a flexible and efficient way to manage and control the output of your PHP scripts. Smarty is not a programming language. It’s a tool that aids PHP programmers to manage their content delivery with ease. It’s particularly useful in scenarios where designers and coders are different individuals in a project. The designer can focus on the presentation part while the coder can focus on coding the logic.

    How does Smarty PHP Template Engine work?

    Smarty works by embedding special Smarty tags within a document. These tags are processed and substituted with other bits of code by the Smarty engine. It compiles copies of the templates as PHP scripts. So, when a template is called, Smarty checks if the compiled version of the template is available and up-to-date. If it is, Smarty executes it. If not, it compiles a new version of the template and then executes it.

    How to install Smarty PHP Template Engine?

    To install Smarty, you need to download the latest version from the official Smarty website. After downloading, extract the files and place them in a directory within your PHP include path. You can also place them in your project directory. After that, you need to set up the directories for templates and compiled templates. Make sure these directories are writable by the web server.

    What are the benefits of using Smarty PHP Template Engine?

    Smarty offers several benefits. It separates the business logic from the presentation logic, making your code cleaner and easier to manage. It provides a range of features like template inheritance and plugin architecture, which can make your development process more efficient. Smarty also has built-in caching mechanisms for improving the performance of your web applications.

    How to use Smarty with PHP?

    To use Smarty with PHP, you first need to include the Smarty class file in your PHP script. Then, create an instance of the Smarty class. After that, you can assign values to Smarty variables and display them in your templates. You can also use Smarty’s built-in functions and modifiers in your templates.

    Can I use Smarty for large scale applications?

    Yes, Smarty is suitable for both small and large scale applications. It’s highly scalable and provides features like caching and template inheritance that can greatly improve the performance and efficiency of large scale applications.

    How to use caching in Smarty?

    Smarty provides a built-in caching mechanism. To use caching, you need to enable it by setting the caching property of your Smarty object to true. Then, you can set the cache lifetime, which is the period for which the cache is valid. You can also clear the cache manually using the clearCache method.

    What is template inheritance in Smarty?

    Template inheritance is a powerful feature in Smarty that allows you to create a base template with blocks of content that can be overridden by child templates. This can greatly reduce the amount of duplicate code in your templates and make them easier to manage.

    How to create plugins in Smarty?

    Smarty provides a plugin architecture that allows you to extend its functionality. To create a plugin, you need to create a PHP file with a specific name and structure, and place it in the plugins directory of your Smarty installation. The plugin can then be used in your templates just like a built-in function or modifier.

    Is Smarty still relevant today?

    Yes, Smarty is still relevant today. While there are other template engines available, Smarty remains a popular choice due to its flexibility, power, and ease of use. It’s actively maintained and has a large community of users.