ent">

Benefits of Smarty Template Engine


Smarty, the not-so-well-known Template/Presentation framework, has been used for years by professional web application developers. It hasn’t caught on so much with mainstream coders – perhaps because of a “why do I need this?” line of thinking. This article will explain why!

 

What is Smarty?

Smarty is a PHP class that provides a fast, scalable, easy, and maintainable presentation framework for displaying and maintaining the design of a website. It enables you to separate design from code by making your site based on cached templates, and provides a way to keep your site’s front-end design uniform and maintainable. So, Smarty not only adds extra maintainability and templating abilities to your project, it also caches it to keep everything snappy and secure!

A Real-Life Example

Let’s say you run a classified ads web application (similar to Craigslist) that is run on Smarty.

  • You have loops that are executed on the front page, which display all the classifieds. You also have variables, such as $sectionName, $title, $categoryTitle, $location etc. which are used on different pages and categories of the ads. Now these variables and loops do not actually do anything with the data – they simply output raw information. This information is passed from the back-end to Smarty without ever touching the frontend. Then, the designer can edit the template and apply his own styles, tables, divs, colors etc. to format the data without even looking at the back-end or the data. Simple, eh?
  • Let us say, one day, you need to change the way that the application delivers data. Perhaps you changed over the database. Or maybe you needed to scale your application, and radically change the back-end business logic of your site. The beautiful thing about Smarty is you can do all that, without even touching any of the front-end design! There is absolutely no difference in the design – you can mess around all you want with the logic of the application without having to restructure the formatting, design or any other aspects of the frontend.
  • Another scenario: you need to update or re-brand the design of your site. Simply edit the template files and formatting – bingo! No need to go through painful PHP code, or restructuring of the backend! Since the backend simply passes data to the front-end via Smarty, no editing is needed except with the design templates that you want to re-brand.

Also, since your website is based on templates, you can make the header, footer, sidebar and other design elements uniformly load from templates – while still keeping your website dynamic.

So..

Basically, Smarty is a template engine. I just want to make it clear, though, that Smarty does NOT replace XHTML/CSS or PHP code – all it does is make the front-end and backend aspects of your project work together in harmony. For more information on what Smarty does, check their official site.

Why Should I Use Smarty?

Some of the benefits of using Smarty are listed below, in no particular order.

1: Maintainability Heaven!

Smarty makes it possible to base your entire website’s design on predefined “templates” which can be reused and changed throughout the project easily. This makes changing and maintaining the design of your site a breeze – it also allows you to reuse parts of the design throughout your project and in other projects.

2: Separate Design From Code

Smarty enables separating frontend from backend code – no mixing in messy PHP code with your site’s XHTML/CSS. Thus, developers and designers can work in harmony. Smarty does this by making it easy to present your dynamic content without messing around with PHP loops and functions within your frontend files. Smarty says on its official site:

“With presentation on its own layer, designers can modify or completely redesign it from scratch, all without intervention from the programmer.”

3: Keep Your Branding and Design Clean

Since it is based on templates, Smarty can help you keep your branded design uniform throughout the project.

4: Make Your Website Loading Snappy

Smarty is faster than a custom templating system, or just manual . This is because Smarty can cache your designs and templates. No need to worry about extra overhead clogging your internets!

5: Better Security

Since you are not opening up application code to the designer, or to the front-end, this can help prevent security flaws as a result of intentional or accidental tampering of code by the designer. It can also help prevent malicious users from examining the way your application works to exploit a flaw in it.

6: Speed up Front-End Development

Not only do Smarty templates make backend integration easy, it also makes it faster. Being relieved of PHP code within the template can be a real boon to designers, and a real time-saver in the long term. Smarty templates make design maintenance easy. As you add more functionality to your front-end (AJAX, jQuery, etc.), Smarty can be a critical lifesaver in preventing your project’s code turning into a nightmare.

7: Manage Complicated User Permissions and Targeted Logic

Let us say you have different user levels on your site, such as “admin”, “premium user”, “regular user” and “guest”, all of which have different permissions to do different things on the page. With traditional PHP on the page, it might look like this:

<?php

if ($loggedIn and ($user_type eq "admin" or $user_type eq "premium user")) { ?>

<input type="submit" value="edit">Edit This</input>

<?php
} //end if

?>

What the above code basically does is check whether the user is an administrator or a premium user, and then shows the edit button.

There are two problems with the above code:

  • You have application logic within the front-end design. If you ever want to change it, say for example, allow any logged in user to edit the page, you have to modify the website’s design files. This may not seem like a big deal, but if you have lots of files, with many different UI options on each page, managing permissions can be a nightmare. Even a few pages with complicated UI can be difficult to manage.
  • The designer has critical PHP code in his files. This can open up security issues, as well as cause bugs if some code is accidentally (or intentionally) modified. It’s also not very pretty.

With Smarty, the above code can look like this instead:

{if $allowedToEdit}
<input type="submit" value="edit">Edit This</input>
{/if}

What’s the difference? There are four significant advantages:

  1. Prettier code. No need to mix tags with the design.
  2. Easier to maintain, since the application logic is separate from the design. If you ever decide to change permissions, you can simply edit the $allowedToEdit variable from the backend, without ever touching the design. This will change the permissions on ALL pages of your site that use that particular template – no need to go scouring through many pages of your UI to locate permissions.
  3. Less chances of a designer messing up the code – it’s easy to understand and self-explanatory. This also makes the code more secure.
  4. Can be faster than using raw PHP. Since variables are passed from the backend, there is no need to access a database from the design. Depending on your usage, variables can be cached, saving a lot of loading time, and relieving some stress on your database.

8: Change or Re-Use Designs on the Fly

This is an obvious advantage of using a template system – designs can be re-used and changed on the fly.

9: Built-in and Custom Smarty Functions – Make Your Template Do More

Many built-in Smarty functions handle tasks such as generating HTML code segments (dropdowns, tables, pop-ups, etc.), displaying content from other templates in-line, looping over arrays of content, formatting text for e-mail output, cycling though colors, etc.. easily without using raw PHP code. If the function you need is not available, you can always create it yourself for using throughout your projects.

10: Community Based Plugins and Add-ons

To drastically speed up development, you can use a growing collection of Smarty add-ons and plugins, such as form validators, data grids and content generator tools as well as many other useful time-savers. See more…

So, is Smarty for me?

It depends on the size and nature of your project. If you’re looking for a complete presentation framework with a large feature set, Smarty is definitely for you. On the other hand, if your project is simple enough, you can roll your own script, or use a CMS. Smarty definitely makes sense for using in large web application which cannot use CMSs for their back-end.

How do I Implement Smarty Into My Project?

Aha! Finally to the meat and potatoes of this article. How do I actually get Smarty working?

To start implementing Smarty into your project, it’s important to have a model in your head of how Smarty works.

Smarty Framework

To get Smarty working, we need to have:

  • A backend file (optional). This file does all the application’s processes.
  • A template file. This will be the design and HTML of the website. Dynamic values are inserted into the design like this: {$value}. You can also use Smarty loops and other display functions.
  • The main file. This file calls the Smarty.class.php and also assigns values to Smarty variables (which were passed from the backend). Smarty takes the values, then compiles the templates and places it into a folder called templates_c. The website is then displayed normally from this file.
  • A config file (optional). This is a .conf file which you can use with Smarty to help manage your website from configuration files. This makes it easier to make changes and maintain your website without touching it’s internal code.

Our first Smarty application: A Little Guestbook

For the purpose of this tutorial, we will implement Smarty into a teeny-weeny guestbook application. Note that I will not actually create the backend and database functions of the application (call me lazy!), as this article is mainly focused on learning about Smarty.

IMPORTANT NOTE: These instructions may be different from other instructions found on the web because it covers Smarty version 2.5.0. Other tutorials are known to cover older versions.

To get started, first download Smarty. Unzip the folder and upload the “libs” directory to your web server. Rename the “libs” folder to “smarty” or something similar; this contains your Smarty classes.

Then create four folders called “templates”, “templates_c”, “configs” and “cache” in your webserver’s www root. Make sure “templates_c” is writable by the web server (CHMOD 700) because it will contain the cached files which the Smarty engine creates. If you want, add the smarty folder to your PHP include_path, so that whenever you write include ‘Smarty.class.php’, PHP will know where to include Smarty from. The SMARTY_DIR constant is the location of your Smarty classes. You don’t HAVE to set it if you just want to include the Smarty classes directly. See the different ways you can set SMARTY_DIR on the official site.

If you decide to use different folder names from the default, be sure to change the settings in the Smarty class. You can do that by writing $smarty->template_dir=’whatever’, etc., after the class is loaded.

File Structure

Your file structure should look something like this (doesn’t have to be exactly like this, but just so you get the idea):

/www.example.com/smarty/
     Smarty.class.php
     Smarty_Compiler.class.php
     Config_File.class.php
     debug.tpl
     internals/*.php
     plugins/*.php

/www.example.com/
     smarty/
     templates/
     templates_c/
     configs/
     cache/
     <span style="color: #0000ff;">index.php</span>

The main file (index.php)

Create a file called index.php in the root of your server. This is the file your visitors will access to view your site.

<?php

//includes and creates the smarty class object
require 'Smarty.class.php'; //assuming you have SMARTY_DIR set or you have the class in your include_path
$smarty = new Smarty;

//turns on caching
$smarty->caching = 1;

//makes sure that a template is not loaded from cache if it has changed
$smarty->compile_check = true;

//includes the backend processing file
require '../controllers/backend.php';
$backend = new Backend;

if ($_GET == 'submit')
$backend->submitEntry($_POST[name], $_POST[comment]);

//assigns a variable to smarty
$smarty->assign("title","SimpleGuestbook: Our First Smarty Demo");

//assigns some more vars retrieved from our backend
$smarty->assign("logged_in", $backend->logged_in);
$smarty->assign("name", $backend->username);
$smarty->assign("guestbook", $backend->gbookArray);

//displays the template
$smarty->display('index.tpl');
?>

(If you didn’t understand any of the above, you probably need to learn object-oriented PHP)

This file starts off by including two classes – the Smarty class and the backend class for the guestbook. We first change some options for Smarty to enable caching. It then assigns appropriate variables for use within the template. The $logged_in Smarty variable is now $backend->logged_in, etc..

One variable is important to note, the $backend->gbookArray. This is basically a PHP array of guestbook data retrieved from the backend which is assigned to Smarty. To give you an idea of how the array looks like, see below.

$gbookArray = array (
array('name' => 'Mr Cool Guy', 'gravatar' => 'http://www.gravatar.com/avatar/333222', 'comment' => 'Nice site!')
array('name' => 'Test', 'gravatar' => '/default.gif', 'comment' => 'Oooh, lovely!')
array('name' => 'Dod33', 'gravatar' => 'http://www.gravatar.com/avatar/dfee2', 'comment' => 'Wow.')
);

Now that we have Smarty fired up, and the correct data passed to it, how does the displaying part go about doing its job?

The templates (index.tpl)

Create these template files in your “templates” folder.

{include file=header.tpl title=$title}

<div class="content">
<p>Hello world!</p>

{if $logged_in}
<p>You are logged in as {$name}.</p>
{/if}

{include file=guestbookForm.tpl}

<table id="gbook">
{section name="gbook" loop=$guestbook}

<tr>
<td class="avatar"><img src="{$guestbook[gbook].gravatar}" title="{$guestbook[gbook].name}" /></td>
<td class="name">{$guestbook[gbook].name}</td>
<td class="comment">{$guestbook[gbook].comment}</td>
</tr>

{/section}
</table>

</div>
{include file=footer.tpl}

There ya go! The template starts off by calling the standard header for your site, and assigning it the “title” variable. Next starts the conent, and then a simple {if} statement displaying the username of the user if he/she is logged in.

Then the guestbook is displayed – first comes the guestbook entry form from a template named “guestbookForm.tpl” . Then the actual data is displayed using the Smarty “section” looping function. As you can see, it’s a fairly easy to grasp syntax. The {section} loop iterates through the $guestbook array, which was assigned to Smarty in the main file, remember? The variables within the array are accessed by first calling the variable ($guestbook), then the section name, (gbook), and then the actual field (name) to give us this: $guestbook[gbook].name, which gives us the current name of the person. This is the standard syntax used for accessing variables within {section} loops: $variable[section name].field

Lastly, the footer is called via the standard {include} function.

header.tpl and footer.tpl contain your standard header and footer. If you like, you may set extra options if the header and footer are different on each page (for example, I set the “title” variable for the header in the above code).

Simple enough?

header.tpl

{config_load file=gbook.conf scope=global}

<html>
<head>
<title>{$title}</title>
<link rel='stylesheet' href='#stylesheet_url#' type='text/css' media='all' />
</head>
<body>

You can see that I have not added any fancy stuff in the header – a lot more is possible than just standard html tags. One important thing to note is the config loaded at the top of the file. This simply loads the configuration file and sets the scope to global (meaning that any template in the application can use its variables). #stylesheet_url# is a variable that is loaded from the config file.

footer.tpl is basically the same story. I will not include it so as not to bore you!

File Structure

/www.example.com/
     smarty/
     templates/
          <span style="color: #0000ff;">index.tpl</span>
          <span style="color: #0000ff;">header.tpl</span>
          <span style="color: #0000ff;">footer.tpl</span>
     templates_c/
     configs/
          <span style="color: #0000ff;">gbook.conf</span> <span style="color: #ff6600;">//optional</span>
     cache/
     <span style="color: #0000ff;">index.php</span>

Is There More?

That’s it! All you have to do is create the guestbook’s backend (which might be the subject of another tutorial), and add some styling. You got a clean, working guestbook application built on Smarty. Note that I stuck with only the most-used functions within Smarty – it can actually do a lot more.

Output

This application will output data similar to this:

<p><span style="color: #ff0000;"><start
	of document></span>
</p>
<h3>SimpleGuestbook: Our First Smarty Demo</h3>
Hello world!

You are logged in as YourUsername.

(show form here)
<table style="height: 90px;" border="0" width="284">
<tbody>
<tr>
<td><img src="http://www.gravatar.com/avatar/40509dbcfd3eddd0544f145af64f6af8?s=80&amp;d=http%3A%2F%2Fpsdtuts.s3.amazonaws.com%2FMisc%2Freader_psdtuts.jpg%3Fs%3D80&amp;r=PG" alt="" /></td>
<td>Mr Cool Guy</td>
<td>Nice site!</td>
</tr>
<tr>
<td></td>
<td>Test</td>
<td>Oooh, lovely!</td>
</tr>
<tr>
<td><span style="color: #000000;"><img src="http://www.gravatar.com/avatar/40509dbcfd3eddd0544f145af64f6af8?s=80&amp;d=http%3A%2F%2Fpsdtuts.s3.amazonaws.com%2FMisc%2Freader_psdtuts.jpg%3Fs%3D80&amp;r=PG" alt="" /></span></td>
<td><span style="color: #000000;">Dod33</span></td>
<td><span style="color: #000000;">Wow.</span></td>
</tr>
</tbody></table>
<span style="color: #ff0000;"><end of document></span>

So what have we accomplished?

  • Your application is much easier to maintain! With an easy-to-read syntax, and all dynamic variables being issued before the template is called, the application is a breeze to maintain (compared to having values and logic mixed in with the application).
  • Want to extend your application? It’s now much easier to do that with templates. Re-use parts of your design, and don’t worry about the hassle of maintaining them. One change to a template reflects it across the entire site.
  • Templates are completely separate from the backend design. You can play around with the backend, and forget about messing up the design, and modify the design without touching the backend.
  • We now have a powerful framework at our hands. With plenty of useful functions, we can easily create a beautiful front-end.
  • Templates are cached – this makes the page load much faster compared to a manual templating system.

What Else Can I Do With Smarty?

As you can see, I only created a really simple application built on Smarty. You might be wondering, “is that all?” No fear, there’s actually much more. Now that you know how to implement Smarty into your project, I strongly recommend checking out all the cool functions that Smarty has, and getting to know them well.

© Scapewebs 2014