Template Engine: An Overview of Smarty Templates & Other Comparisons

The template engine's job is to help separate out application model logic from display logic and to provide a simpler, more readable way to add functionality to your display files. Since HTML was never meant to handle arbitrary logic, it is generally kept separate from the Model and Controller layers of an application - learn more about MVC.

Template Engine: An Overview of Smarty Templates & Other Comparisons


However, it's inevitable that at least some presentation logic gets mixed up into the HTML template file due to requirements such as "Alternate background color of each table row" or "Show only positive balances". So, rather than mix standard PHP code into the HTML template file, template enginhowes were conceived which mask common PHP functions and tasks with more presentable and concise code and allow for a deeper separation of logic and markup.

Standard HTML Template vs Template Code

So while a standard HTML template might contain code like this:

<?php foreach ($items as $item): ?>
<div><?php echo $item; ?></div>
<?php endforeach; ?>

Template code might look more like this:

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

As you can see, the latter would be much more readable by non-coders and looks more like typical markup than PHP code. But although the code may be prettier, one of the criticisms for using a template engine is the extra resources and time spent compiling the template code into actual PHP code. This really is a give and take. If you are a sole developer working on a project and you don't really foresee having more than a few developers working on the project at a time, then maybe a template engine isn't for you. On the flip side, if you end up having multiple developers and front end coders editing your code later on, a template engine could be a huge benefit.

While there are many template engines out there, some stand out among the others. Smarty Template Engine is one of the older engines that has been scrutinized and improved upon year after year. Because of its age, there is a wealth of resources for solving Smarty problems across the net.

Smarty vs Other PHP Template Engines

Smarty describes itself as a Template/Presentation Framework. Its goal is to not to be a simple tag-replacing engine, but a full-featured template engine that allows for simpler, more painless development without sacrificing speed, security or performance. So, does Smarty live up to its definition? Well, let's see how it stacks up against the other template engines out there. Here is a quick comparison with a few of other popular PHP template engines.

Smarty Template

PHPTAL

One thing I have always noticed about Smarty is that it is usually pretty easy to find answers to you question with a quick Google search or a search in the Smarty forums. PHPTAL doesn't seem to have quite the wealth of information enjoyed by Smarty users, but I guess that comes with popularity. What PHPTAL does well, however, is template syntax. It just seems a little bit more logical and readable than Smarty.

PHPTAL

Here's a simple foreach statement in Smarty and PHPTAL.

Foreach in Smarty:

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

Foreach in PHPTAL

<div tal:repeat="item items" tal:content="item">
this is just example content and is not required, kind of
like a comment. Neat!
</div>

There are tons of really cool features available in PHPTAL that make it a fairly strong template engine but Smarty definitely seems a bit more beginner friendly, though not quite as powerful as PHPTAL.

Dwoo

Dwoo is a template engine created in 2008 in direct opposition to Smarty. Smarty still supports PHP4 and doesn't take advantage of some of the object-oriented features of PHP5, so Dwoo was created as a modern alternative to Smarty. Since Dwoo is not nearly as old as Smarty, there are naturally a lot more resources on the internet for help with Smarty templates. However, Dwoo, being a more modern engine, is focused on speed and utilizes template inheritance as a main feature. The syntax for the two engines is similar, which makes sense since Dwoo was created as a direct alternative to Smarty.

Dwoo

Foreach in Smarty

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

Foreach in Dwoo

{foreach $arr val}
<div>{$val}</div>
{/foreach}

Savant

Savant describes itself as The simple, elegant, and powerful alternative to Smarty and takes a much simpler approach to templating. Savant doesn't utilize its own pseudo-language for its template files but rather relies on standard PHP code. Because of this, there is no caching for compiled PHP scripts like Smarty and no pre-filtering or post-filtering is required since all templates are written in standard PHP code. This means that Smarty's code (as well as many other template engines that utilize pseudo-code) is shorter overall.

Savant

Foreach in Smarty

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

Foreach in Savant

<?php foreach ($myArray as $foo): ?>
<?php echo "<div>$foo</div>" ?>
<?php endforeach; ?>

So what is the point of using a Template system like Savant? To separate your application model logic from your display template logic. It's as simple as that. Is it better than a template engine that uses a pseudo-language like Smarty? That's really up to you to decide!

Rain TPL

Rain TPL is a fairly lightweight template engine that was released back in 2007. While it doesn't seem to be as feature heavy as Smarty, it does use a fairly similar syntax that will make Smarty users feel right at home.

The Rain TPL website has decent documentation but there doesn't seem to be an active forum for the software. This is a huge disadvantage when it comes to troubleshooting. It seems that if you are working on a fairly simple project then Rain TPL could be a decent solution but if you are looking for a template with a more refined and feature heavy pseudo-language with community support, Smarty is the way to go.

RainTPL

Foreach in Smarty

{foreach from=$myArray item=foo}
<div>{$foo}</div>
{/foreach}

Foreach in Rain TPL

{loop name=”myArray”}
<div>{$value}</div>
{/loop}

Overall, what Smarty lacks in speed or features, it makes up for in resources and ease of use. I have yet to run into a problem in Smarty that couldn't be sorted out by using a few caffeine-powered keywords in a Google search or by checking out the Smarty forums.

Setting Up Smarty Templates for Your PHP Project

Here is a step by step guide that will get your PHP project up and running with Smarty Templates in minutes.

  1. Head over to Smarty Download page and grab the latest stable release.
  2. Create /smarty within your root directory of your project, in my case c:/wamp/www/projectname.
  3. Unpack the contents of /libs from the Smarty pack you just downloaded into /projectname/smarty/libs.
  4. Create the following directories inside of /projectname/smarty
    • templates
    • templates_c
    • cache
    • configs

That's it! Now let's initialize Smarty and get it setup. Paste the following code into index.php file in /projectname.

<?php
    // importing the Smarty class
    require_once('smarty/libs/Smarty.class.php');

    // now make an object of the class
    $smarty = new Smarty();

    // mapping smarty directories
    $smarty->template_dir = 'smarty/templates';
    $smarty->compile_dir  = 'smarty/templates_c';
    $smarty->cache_dir    = 'smarty/cache';
    $smarty->config_dir   = 'smarty/configs';

    // assigning values to variables and displaying using template
    $smarty->assign('greeting', 'Hello');
    $smarty->display('index.tpl');
?>

Now let's create our first template file. Within /smarty/templates create index.tpl and paste in the following code.

<html>
   <head>
      <title>First Smarty Template</title>
   </head>
   <body>
      <p>{$greeting}!</p>
   </body>
</html>

If you see "Hello!" outputted on the screen then Smarty has been setup successfully.

In our example we put our templates folder inside the smarty directory but remember you can assign that to whatever you'd like by assigning the directory path to $obj->template_dir. The same goes for cache and config directories.

How Is Smarty Going to Help You?

Smarty mayhave be a bit of a learning curve at the beginning but the more you work at it, the faster you will develop your front-end. Most of the basic Smarty functions, such as assigning variables, if else, foreach, counters, etc. can be found by searching the Smarty manual. The Smarty forums are also a great resource. Chances are there is someone there who has had the same problem you are having.

Within a few days you should start noticing the organizational benefit and hopefully an increase in your development time. You may also find an even greater advantage to Smarty when working within a team. Since some team members have front-end developers who aren't familiar with PHP or syntax, it is usually much easier for them to work within a Smarty template than a standard HTML file with PHP code integrated. Smarty is made to be more readable and concise, leaving less room for error.

Resources to Help You Become a Smarty Pro

While Smarty may have its short comings, the wealth of community and support rallied behind this project more than makes up for them. This is a refined and easy to use template system that gets better and better with each release. It has been around for years and doesn't seem to be going anywhere. Let us know what you think about Smarty Template in the comment section below.

Opinions expressed in this article are those of the author and not necessarily those of Onextrapixel.