Working ‘Smarter’ with Templates

Managing hundreds or even thousands of individual pieces of web content is difficult in itself, but when you add the necessity to format all of this content and keep it light on its feet for site redesigns, make it accessible for searching, and loosely coupled for restructuring, the task becomes all but impossible. It is only through a template system that we begin to feel the content choke hold loosen ever so slightly.

How Templates Work

Template systems allow us to separate the application and presentation aspects of our websites. When many developers hear the word “template” they imagine a set of rigid, dry wire frames that are designed to steal their creativity and mute their expressive ability. I fully understand this perspective as I have seen great template systems fail by being deployed in this way. The good news is that when templates are structured with some imagination, they can offer the desperately needed structure and consistency without hamstringing your design and development process.

Most template-powered web pages have two basic parts – the php script that the visitor calls with their browser, and the html page that the php script loads and displays. The programmer sets up the code to populate the necessary variables, structures, recordsets, etc. in the php script, and the designer simply consumes them using special variable “placeholders” in the html template file. This means that the designer needs no coding skills and the coder needs no designing skills.

This works out nicely, as this seems to be the case in many of the development environments I have seen. I was recently involved in a website build where the programmers of the site were onsite while the designers were a time zone away. The amazing thing is that all communications were handled with instant messaging and email. Everyone got to focus on what they did best, and there was very little overlap between programming and design. This exemplifies the power of the template engine. Using templates simply makes sense, but with so many template systems out there, how do you know which is best?

When choosing the right template engine for your projects, there are a few critical requirements that should be considered:

  • Extensibility
  • Licensing Model
  • Speed
  • Functionality
  • Usability (Time to deploy)
  • Support

Enter Smarty

Smarty is a template engine developed for php. Smarty meets all of the above criteria with flying colors.

  • Smarty is highly extensible through its plug-ins model and large set of available functions.

  • Smarty is licensed under the LGPL licensing model (open source) which most developers are familiar with. The real beauty of this licensing model is that developers are able to redistribute their work as proprietary software with no licensing conflicts.

  • Smarty is extremely fast (especially with the release of 2.0). Visit http://smarty.php.net/benchmarks/ for some interesting benchmarks on Smarty performance. I have seen Smarty used on extremely busy web servers without a hitch. Smarty’s caching capabilities ensure that templates are only compiled when changes are made thus greatly increasing performance.

  • Smarty is loaded with functionality. Once you get the hang of it, Smarty can greatly increase the development time of your projects.

  • Though the learning curve is not insurmountable, it will take any developer some time to fully exploit the power of Smarty.

  • Smarty is very well documented and supported through the smarty.php.net website. Their support site contains a quick start guide, many samples, installation instructions, and much more information.

To understand the value of Smarty, we first look at how a simple task would be carried out in traditional PHP scripts without using a template system.

<html>
<head>
<title>Show IP</title>
</head>
<body>
<?
// ShowIP.php
echo $_SERVER['REMOTE_ADDR'];
?>
</body>
</html>

As you see, we simply create a basic web page and add the necessary php to display the IP address of the visitor. This is a fine method for such a simple task, but as you’ll see, this method can become very cumbersome when you begin to introduce HTML into the php output. Take a look at the following example and notice how much more confusing the code becomes when we introduce some html into the mix.

<html>
<head>
<title>Show IP</title>
</head>
<body>
<?
// ShowIP.php
echo “<a target=”_Blank” class=”linktext” href=”http://” . $_SERVER['REMOTE_ADDR'] . “”>Click Here to view server</a>”;
</body>
</html>

Escaping those quotes and concatenating for the variable makes for some messy code. This is just the beginning – imagine the carnage if we add tables, more classes, loops, more variables, etc.

The concept of templates can be hard to grasp at first so sometimes it’s best to just dig right into the code. Assume that you have a simple script that displays the IP address of the visitor. There are a couple of ways to display this information, but in this example we will use a template via Smarty. Let’s take a look at this typical use for a Smarty template page. Note that this example requires that Smarty is installed on your server. This process does not require compiling – simply unzip the smarty files to a location of your choice.

// ShowIP.php
// Include the necessary Smarty files
include(“/path/to/Smarty/libs/Smarty.class.php”);
//Create the Smarty object
$smarty = new Smarty();
//Set the compile check to true
$smarty->compile_check = true;
//Choose your delimiter types
$smarty->left_delimiter = “{{“;
$smarty->right_delimiter = “}}”;
//Set your directories
$smarty->template_dir = “/path/to/Smarty/templates/”;
$smarty->compile_dir = ‘/path/to/Smarty/templates_c/’;
$smarty->config_dir = ‘/path/to/Smarty/configs/’;
$smarty->cache_dir = ‘/path/to/Smarty/cache/’;
// Assign a smarty variable with a value
$smarty->assign(‘VisitorIP’, $_SERVER['REMOTE_ADDR']);
// Parse and display the template
$smarty->display(“showiptemplate.htm”);
?>

Note the total lack of HTML in the above example. This is a beautiful thing for creating sites that can be easily re-skinned. I know that this is a very basic example, but believe me when I say it scales wonderfully to the most complex of web pages with no trouble. The real trick with Smarty is resolving to never mix your code and HTML. You will be tempted to put “just a little” html in your php scripts at times, but in almost every case, you’ll find yourself getting back in there later and ripping the code out. You’ll only truly leverage the power of Smarty when you totally buy in to this separation principle.

Below is the template file that the script above would load and display:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<title>Show IP</title>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1″>
</head>
<body>
<a target=”_Blank” class=”linktext” href=”http://{{$VisitorIP}}”>Click Here to view server</a>
</body>
</html>

 

CMS Systems

The very nature of a CMS system screams “Templatize me!”. I’m sure that nearly all CMS systems use some form of templates, but Smarty really out-performs most methods that I have seen used.

When Used with Pear (PHP Extension and Application Repository)

Pear allows developers to leverage the power of a huge mass of the php development community when building their site. Many PEAR modules are built with Smarty in mind. As a side note; a site I built recently had to be ported from PostGreSQL to mySQL. This change could have been quite ugly, but since I had used PEAR for all of my database abstraction, the entire conversion took less than an hour.

When Developing in a Distributed Environment

Smarty does such a great job of separating the code from the design (application from presentation) that little dialog needs to take place between the code developer and the HTML design/production team.

Doing comparisons in a loop (section)

It’s best to do your comparisons in your php and pass the final recordset down to Smarty. This greatly improves performance. This really applies to anything you would do with smarty in a section loop. If possible, do your programming in your php and pass a ready-to-go recordset to Smarty.

Mixing “Some” HTML into your PHP code

It is almost unavoidable to put some HTML into your PHP code, but you must resist this at every opportunity. As more and more HTML begins to creep into your PHP you will find the benefits of templates diminishing.

Overuse of Smarty Functions

Many developers become so enamored with the convenience of the Smarty functions that they tend to overuse them in their templates. Too much of this behavior and you have the same problem that you had before templates only with a whole new subset language – not the ideal situation.

“Some” Templatizing

Using templates doesn’t have to be an all-or-nothing proposition, but templates become more hassle than they are worth when used in some areas of the site but not in others. This practice leads to several versions of the same page lying around waiting to make your life miserable down the road.

Wrapping it Up

If you’re looking to simplify/streamline your design and development process, templates are definitely one of the major components to reach that goal. Of the various templates out there, I chose Smarty. My suggestion to you would be to try a few of them on small projects and come to your own conclusions about which system might be right for you. If you decide to give Smarty a go and need a hand here and there, don’t hesitate to give me a shout by clicking on the Discuss link for this article and I’ll help where I can. Also, if interested, I can provide many real-world examples of more advanced uses of Smarty.

Google+ Comments

Google+ Comments