Template Engine: An Overview of Smarty Templates & Other Comparisons

Template Engine: An Overview of Smarty Templates & Other Comparsions

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.

Eric Bieller is a web developer/designer and internet entrepreneur with a passion for both front-end and back-end who loves creating new internet services and technologies that make life both funner and easier. He also enjoys learning new things and sharing what he knows with others.

Comments

    • Tom,
    • July 6, 2010
    / Reply

    You have forgoten to COMPER Template Parser. The CI version is pretty nice, and I think in two weeks new version will be relaeased. I like it because it’s small and light-weight.

      • Eric,
      • July 6, 2010
      / Reply

      I’ll have to check that out. I’m a CakePHP user myself. I don’t think Cake comes with any template engine integrations out of the box but I have seen posts on how to integrate it with Smarty. I generally just do standard PHP templates with Cake though.

  1. / Reply

    Wow, I must say very nice designs. Today web designing is growing day by day and it is very important that website must be very appropriate with it subject. Here given examples are superb and very well designed. Nowadays people need more and more creative designs. These all are really very nice examples. I really appreciate that you had shared this.

      • sid,
      • July 15, 2010
      / Reply

      wtf.. what did this post have to do with design? did you even read it?

    • pcdinh,
    • July 7, 2010
    / Reply

    Smarty???? Is it 2001?

    Please, Smarty is bad, Smarty is dead

    http://nosmarty.net/

      • Eric,
      • July 7, 2010
      / Reply

      Thanks for your input! It’s inaccurate to say that Smarty is dead when 3.0 RC2 was just release in June. Also, in my opinion many of the remarks on nosmarty.net are fairly trivial. Smarty definitely isn’t for everyone (in which case you should try one of the other engines mentioned) but it can come in handy in some instances. Just depends on your dev environment and goal.

  2. / Reply

    Wow A great article on time.

    Last night i was scratching my head with CodeIniter.

    Okay one question what about CodeIniter i am newbie in web development i know basic php stuff what would you recommend me to go with Smarty or CodeIniter?

    Thanks

      • Tom,
      • July 8, 2010
      / Reply

      Hey!

      I’m using CI for a months, so you can use Smarty, but it’s up to you. For me it has got many unuseful functions and bad-writed docs.

      Then you can use another Template Engines, but they don’t have enought functions (for example many of them provide ‘if-else’ statements, but a few provide ‘if-elseif-else’). And many of them use PHP on their templates. But … why are templates good? You can make just PHP files called View layer, but I think Templates are good for designers. And designer don’t have to understand PHP. That’s why, I recommend COMPER Template Parser. It’s no.1 for me, because it’s small library, got needed functions, easy docs and I think new version will be extendable. It will be great!

  3. / Reply

    Nice list, although none of the engines do what they should do: “Seperate code from design”
    The only thing they do is rewrite basic PHP functionalities to even worse coding…

    In my opinion a template file should be able to be useful without any PHP involved and should be able to validate even without running it through the engine. This can be done by using a block-template which uses HTML comments as block names (and even include definitions) and simple “{var_name}” tags to replace the content.

    Please note the PHP is a template engine by itself, since it’s: “PHP: Hypertext Preprocessor” which means it’s processes hypertext (same ‘H’ as is HTML) before sending it to the browser.

      • Eric,
      • July 7, 2010
      / Reply

      Some good points. You’re right that some engines don’t technically separate the logic out of the view but they generally aim to mix the two together in a more readable way (which might be less readable to some but it just depends on who’s looking).

      Template engines do add extra processing but there are simpler ones like Savant that don’t actually have their own pseudo-languages. Some might be better suited with an engine like this.

      In most scenarios it is inevitable that loops and if statements get mixed up in the view but it’s generally not enough to make me feel like I’m violating the MVC pattern.

  4. / Reply

    I do agree with Johan. The only purpose of a templates is to separate business logic from view logic and for the view to be completely independent no code must be present in the template. Using a block-template is a good solution.It would make the template really independent but would add a slight weight to the controller .

    I think that using php in your template is better than using any other template language(like smarty) that needs to be run trough another processor creating a more complex route for the same result. I like the way Zend Framework (Zend_View) handles this problem.

    • Baukereg,
    • July 7, 2010
    / Reply

    I still stick to using PHP in my templates, because:
    a) The extra compilingprocess adds to the loading time, and I usually work on pretty big projects
    b) Most front end developers have no problem with distinguishing PHP code from the actual HTML

    My templates usually look like this:

    <input type='hidden' name='’ value=” />

      • Eric,
      • July 7, 2010
      / Reply

      Well an engine like Savant doesn’t actually use it’s own pseudo-code or do require any pre-processing and it’s pretty lightweight so perhaps that would be a better solution for you?

      1. / Reply

        Actually, All of the template engines you mentioned process before the page is shown. HAML PHP is way better as i can compile to php -> output php rather than output a process.

        Saves time.

    • Simon,
    • August 10, 2010
    / Reply

    Thanks for the article, I hope more and more developers are going to use Smarty :)
    By the way, just to point it out, Smarty 3 is PHP5.

    For people mentioning compiling time and so on, I guess you never really had the opportunity to take a closer look at Smarty. Compiling is done once, and then not done any more until you edit the templates. So no, there isn’t a waste of time caused by compiling. Not to mention the cache functionality offered by Smarty.

    1. / Reply

      Yeah I didn’t really go into much detail about caching but Smarty does cache template output until it’s updated so that definitely needs to be taken into consideration.

    • salvatore,
    • August 25, 2010
    / Reply

    The question are syntax question.

    Syntax comparison:

    Smarty
    {foreach from=$myArray item=foo}
    {$foo}
    {/foreach}

    Tal

    Savant

    <?php echo "$foo” ?>

    Dwoo
    {foreach $arr val}
    {$val}
    {/foreach}

    Rain Tpl
    {loop name=”myArray”}
    {$value}
    {/loop}

    PHP
    <?php foreach ($myArray as $foo) echo "$foo”; ?>

    I prefere PHP: light, fast, readable, no extra library required.

    The only alternative candidate are Tal, but Tal are not independent powerful language as PHP at this moment.

    Why I need to overcomplicate my code?

    • salvatore,
    • August 25, 2010
    / Reply

    The question are syntax question.

    Sorry: for some reason the before comment have a mistake :-/

    Syntax comparison:

    -Smarty
    {foreach from=$myArray item=foo}
    {$foo}
    {/foreach}

    -Tal

    -Savant

    <?php echo "$foo” ?>

    -Dwoo
    {foreach $arr val}
    {$val}
    {/foreach}

    -Rain Tpl
    {loop name=”myArray”}
    {$value}
    {/loop}

    -PHP
    <?php foreach ($myArray as $foo) echo "$foo”; ?>

    I prefere PHP: light, fast, readable, no extra library required.

    The only alternative candidate are Tal, but Tal are not independent powerful language as PHP at this moment.

    Why I need to overcomplicate my code?

    • salvatore,
    • August 25, 2010
    / Reply

    Sorry… but the PHP tag create a mistake and not visible right code :-/
    + the div are omitted by the system from my original text :-/

    Are impossible to write a right code inside this comment :-/

    but if we understand PHP we know the right code :-)

    1. / Reply

      Hi Salvatore,

      You can wrap the code with code tag in the comment, or you can send us an email through our contact us page and I will try to update it.

      Thank you.

  5. / Reply

    I use smarty since 2005.
    I integrate smarty 3 in Magix CMS with great pleasure.
    The syntax is really simple and attractive, its development is rapid in recent months and I do not want change.
    Thanks smarty;)

  6. / Reply

    I have used Smarty for all my big projects the last years.

    Smarty must be the best template engine ever created.

    Smarty 2 was pretty bloated – but worked perfectly.
    – Now that STABLE release of Smarty 3 is released; PeecFW Content Management System & Framework is using Smarty 3.

    What do I like about Smarty 3?:
    – Template syntax is logical, and is very simple. You don’t have many restrictions.

    – Smarty actually supports real caching features (Php compile cache and Static HTML caching) The HTML caching feature is bullet proof and elegant.

    – Many Static HTML caches of a simple tpl file, helps when having big CMS systems and you want to cache many articles using the same tpl file!

    – Smarty 3 has logical OOP structure.

    – The ability to create dynamic database content from Smarty with fetch() method you can easily genereate cool content based on the PHP logic (even in a news article).

    – Ability to easily create recursive content such as recursive menues and tables. Recursive content generation is a must these days.

    I can only say to Smarty Devs:
    Continue the development of the best template engine out there, great job on releasing Smarty 3.0.

    Thanks!

  7. / Reply

    Nice writeup, albeit some more hard-data would make it even more useful (basic comparison of template features, speed in rendering a test template and memory used).

    One notable player missing: the Zeta Components template!

    • Rain,
    • April 9, 2011
    / Reply

    Eric in the review of Rain TPL wrote a critic:
    ” … doesn’t seem to be an active forum for the software. This is a huge disadvantage when it comes to troubleshooting.”

    now RainTPL implements a community forum:
    http://www.raintpl.com/Forum/

    • rocker_boi,
    • April 21, 2011
    / Reply

    Savant3 works great for me i looks the same on wordpress themes that i see.

Leave a Reply

Your email address will not be published. Required fields are marked *

Deals

Elegant Themes Coupon Code: 20% discount

While most other WordPress theme sites charge per theme, Elegant Themes is an amazing deal as you pay just once for access to 87 premium WordPress themes and a…

WrapPixel Coupon – 25% Discount

If you’re looking for an HTML or PSD template for your next website, checkout the selection of templates at WrapPixel made for web developers, designers, and agencies. You can…