File Under: Programming

Keep Sites Clean With Smarty

One of the main advantages of systems like PHP, XSSI, and CSS is the way they let us keep the functional code (or “business logic” as the eggheads call it) separate from how the content is rendered (“presentation”). At least in theory.

In actuality, this separation happens all too rarely, and muddled code with everything scrambled together is the norm. That kind of separation becomes especially important when multiple people are involved in a project, with designers, programmers and content writers working separately. Or, when you need to make frequent changes to, say, the look of a site without changing its wording, or vice versa.


  1. The Basic Smarty Template
  2. Installing Smarty
  3. Building a Smarty Page
  4. Template Tricks

The Basic Smarty Template

Smarty makes separation much, much easier by layering a templating system on top of PHP. This allows flaky designers, unwashed programmers and who-needs-’em content monkeys to all do their own thing without even seeing, let alone stepping on, each other’s toes. A Smarty template acts as the intermediary between all of them. The template consists of a designed HTML page with slots for content that can be filled dynamically.

An example of a template will clarify how this works:




 How to recognize {$name}



 <body bgcolor="#000099">

 {$name}'s hair is {$haircolor}. He or she wears {$shoecolor} shoes.



The snazzy look of that template was created by a brilliant design team on giant CRT monitors, and the data inside the curly brackets is fed in from a PHP script created by a part-time web programmer with a burrito tattoo. The two have never met, and they like it that way.

Naturally, templates typically get quite a bit more complex than that. But let’s start by installing Smarty.

Installing Smarty

All you need to get started is a web server running PHP. Download the latest release of Smarty from the download page, and untar the package:

 tar xzvf Smarty-x.y.z.tar.gz

It contains several directories, including an important one called libs:place that in its entirety somewhere in your PHP include path.

If you don’t know where your include path is, it can be found by reading the output of the PHP function phpinfo(), and it can be modified in the php.ini file (if you have access to that on your server) or with the ini_set() function (if you don’t).

Alternately, you can put it any old place and refer to its location specifically every time you include() it. The libs directory contains the functional heart of Smarty, the PHP classes that do the work.

Next, create a web-accessible directory where you are going to build your first Smarty template. In this directory, create three subdirectories, called templates, templates_c and configs. Smarty uses these to work its magic, as we shall see.

The installation of Smarty is now complete. You will have to reboot your server. Just kidding!

Building a Smarty Page

Two components are required for a Smarty page:a template file, which ends with a .tpl suffix, and a PHP file that invokes Smarty and gives values to the template variables. Going back to our hypothetical designer and programmer, the designer messes around with the template file to her heart’s content to control the looks of the page, and the programmer handles the PHP (and MySQL or what-have-you).

Let’s start with that template page up top. Save it in your templates directory (that is where all templates should live) under the name recognize.tpl. Then, wearing our Programmer hat, we will breathe life into it by creating a basic PHP file, called recognize.php:


First we need to pull in the Smarty class:

 require 'Smarty.class.php';

If you didn’t put the libs directory in your include path like I told you, you’ll have to specify ‘/path/to/Smarty.class.php‘ explicitly.

Then we create a Smarty object from the class:

 $smarty = new Smarty;

Every Smarty script begins in roughly this way. Now we can begin assigning values to variables, using the assign method of the Smarty class. In practice, these values will come from a database or other dynamic source.

 $firstname = 'Sandra';

 $smarty->assign('haircolor', 'auburn');

 $smarty->assign('shoecolor', 'taupe');

 $smarty->assign('name', $firstname);

Finally, we use the display method to call and display the template, nicely filled in with the values we assigned:



End of script. Here’s a clean copy:


 require 'Smarty.class.php';

 $smarty = new Smarty;

 $firstname = 'Sandra';

 $smarty->assign('haircolor', 'auburn');

 $smarty->assign('shoecolor', 'taupe');

 $smarty->assign('name', $firstname);



If you launch and you’ve done everything correctly, it should display a finished page saying that:

 Sandra's hair is auburn. He or she wears taupe shoes.

The first time Smarty displays the page, it also compiles the output into a PHP page and stores that in the templates_c directory. That makes everything run faster, since the Smarty engine doesn’t have to parse the template again until it’s changed.

Congratulations! That’s your first Smarty page!

Template Tricks

If that was all Smarty could do, it’d be kind of nifty but probably not worth a Webmonkey article this long. Since this article is still unspooling, we can therefore deduce that there’s more to Smarty, much more. A host of template functions are provided that make Smarty a genuinely robust way of doing things. Let’s put on that stylish Designer hat again.

Working with a template, we aren’t limited to simply grabbing variable values from the PHP script and displaying them in nice colors. The display of variables can be changed dynamically in the template with a variety of modifier functions. For example, to convert the value of a string to all caps, we can use a reference in the template like this:

 I said, {$name}'s hair is {$haircolor|upper}!!!

The |upper causes the value of $haircolor to be displayed in uppercase:

 I said, Sandra's hair is AUBURN!!!

There are a number of other useful modifiers. Truncate is awfully handy when you want to display strings of varying or unknown lengths in a confined space:It chops off the end of the string at a length you specify. So if your template reads:

 My favorite foods are {$foods|truncate:15}

The output will be:

 My favorite foods are zucchini, lemons...

regardless of how long the actual content of the $foods variable is. That “15″ in the template is an argument telling truncate how many characters to cut off at. You can pass additional arguments to change the appended text (“…” is the default) and to specify whether to chop off the string at the preceding word boundary or right in the middle of a word (“false” does the former, “true” the latter). Thus {$foods|truncate:5:"-aagh!":true} will cut off the string at five characters, regardless of whether the word is done or not, and append “-aagh!” to the truncated string:

 My favorite foods are zucch-aagh!

As you can see, the colon character : delimits arguments.

Wordwrap is used to word-wrap long strings, and also takes three optional arguments, specifying:the number of characters before wrapping (default is 80); what to put at the end of each line (default is n, the newline character); and whether to break lines at word boundaries (the default) or just exactly when the character count is met. So, to insert
tags in a string every 40 characters, without respect for word boundaries, we use:{$string|wordwrap:40:"

One more:regex_replace allows for actual text replacement in the template. It uses the same syntax as PHP’s preg_replace() function. That is to say, it takes two arguments:first the regular expression for which to search the string, and second the text to replace it with. So, to replace every instance of the word “color” with “colour” and then put the string in all caps (sorry, not all these examples can be hilarious ones) we’d say {$string|regex_replace:"/color/":"colour"|upper}. Notice how I tacked a second modifier, upper, onto that. When multiple modifiers are used, they are evaluated from left to right.

The arsenal of variable modifiers gives designers a nice little dose of power over the content. There’s more where that came from:Stay tuned for our intermediate Smarty course, in which we’ll cover advanced tools for template designers, like if/else statements and for loops; as well as some features for programmers to play with.