#native_company# #native_desc#
#native_cta#

Smarty Templating System

By Ben Robinson
on April 13, 2007

Introduction
The Smarty templating system is a fantastic framework for architecting php-based websites, especially in a collaborative development environment. This article will examine the benefits of Smarty, as well as delve into some basic examples of its implementation. We will also point the way to the available resources and community based around the system. First, let’s make the case for Smarty.

Why smarty?
  1. Templating: Smarty has a great tagging system to simplify common tasks in both html and in php coding. The templating system also (largely) keeps separate the php code from the presentation layer. For designers, you can also add tweaks to dreamweaver to allow the editor to ‘see’ the template file in WYSIWYG mode.

    Separating code from presentation is a huge deal in any project, from small to large, and it is an excellent techqnique to become accustomed to if you haven’t already. Smarty templating is a great way to introduce yourself to this.

  2. Simplicity: The smarty templating system allows for very short tagging syntax to greatly simplify your output logic. Here is an example for an image tag:

    This: {html_image file=”masthead.gif”} is equivalent to this:
    <img src=”masthead.gif” border=”0″ height=”48″ width=”256″>

    You can probably see right away how you don’t need to worry if the image size changes a little (keeping in mind of course how broad a range of image sizes your layout template could handle).

    Also, logic on pages is quite simple as well, which we will demonstrate in the guestbook demo shortly.

    Once you set up a framework in smarty, making sitewide changes becomes much easier for both the designer and the coder.

  3. Object registration and security features: The smarty codebase has the ability to register objects that you have created or loaded in as plugins to it, making output tagging extremely simple. There are also added security features to this which allow you to register objects, and specifically only the methods you want publicly available to the templates. Refer to the smarty documentation for more info on this.
  4. Smarty is highly customizable: The Smarty framework is set up by nature to be customized to the users specifications, from codebase locations, to custom tagging, to plugin code, etc. It is probably some of the most flexible code I’ve seen in such a small package, quite impressive really.
  5. Caching: The smarty system has sophisticated caching abilities, from template caching, to intelligent caching of page output, cache grouping, etc. This is a great feature to have available, especially for larger and/or heavily trafficked sites.
  6. Lots of successful sites and cms packages use smarty: If you are a developer, putting smarty on your resume greatly increases your profile–as many larger sites and development firms out there, as well as widely used content management systems (XOOPS, etc)–are using it. Showing that you have implemented frameworks in smarty (especially your own custom setups) is an indication that you are a serious developer who uses proper design methodology, and can make you a highly sought after coder.
Setup
Download the code sample and extract it to your web directory. Before you get started, open up demo/index.php and look at line three:

require ‘../libs/Smarty.class.php’

the default (from the regular smarty download) wants you to use your /var/lib/php/smarty directory, but if you have a virtual server you do not have access to this. The code example for this article has this relative path set for you.

You also need to add the directory in the demo folder called templates_c and make sure it’s writable, as the program will be expecting it. This directory is where smarty loads your template files and compiles them for quicker execution (refer to the the smarty manual for more info about caching).

You should be able to load the page from http:///smarty/demo/ and see the example output. This is an extremely simple example of how smarty works. Take a quick peak at the code in the index.php page in conjunction with the template files (demo/templates/) to get a quick overview of what’s going on here. I would like to use the guestbook example to show how smarty can interface with a database.

The code example for this article has the guestbook demo integrated with it, also containing a tweak to use mysqli instead of PEAR DB, so if you download the original demo archive for the guestbook app, you’ll see some subtle differences. Don’t forget to run the guestbook sql script so you have the database there! (demo/guestbook/sql/)

Let’s take a look at the template file for the guestbook page (demo/guestbook/templates/guestbook.tpl):

{* Smarty *}

<table border="0" bgcolor="#eeeeee" width="300">
    <tr>
        <th colspan="2" bgcolor="#d1d1d1">Guestbook Entries (<a href="{$SCRIPT_NAME}?action=add">add</a>)</th>
    </tr>
    {foreach from=$data item="entry"}
        <tr>
            <td>{$entry.Name|escape}</td>        
            <td align="right">{$entry.EntryDate|date_format:"%e %b, %Y %H:%M:%S"}</td>        
        </tr>
        <tr>
            <td colspan="2" bgcolor="#dedede">{$entry.Comment|escape}</td>
        </tr>
    {foreachelse}
        <tr>
            <td colspan="2">No records</td>
        </tr>
    {/foreach}
</table>

The dynamic tags look a little strange at first, but the more you get accustomed to them, the more you will appreciate the simplicity of the smarty tagging system (which, as mentioned, is highly customizable as well).

Take note of the $data variable; this is passed from the index page in the command:

$guestbook->displayBook($guestbook->getEntries());

which does this (in libs/guestbook_lib.php):

function displayBook($data = array()) {

        $this->tpl->assign('data', $data);
        $this->tpl->display('guestbook.tpl');        

    }

The assign command is using a smarty assignment method to allow your template file to access the $data array obtained from the getEntries function, which just does a select * on your guestbook table and then prepares the array for smarty to loop through:

function getEntries() {
    	
    	$out = array();

        $result = $this->sql->query(
			"select * from GUESTBOOK order by EntryDate DESC"
		);
		
		while ($row = $result->fetch_assoc()) {
		array_push($out, $row);
		}
		
		//print_r($out);
        return $out; 
    } 

the next line:

$this->tpl->display('guestbook.tpl');

tells the system to display the guestbook template.

Taking a close look at how this code is organized will really get you started in how sophisticated you can get with this system. Take special note again of how simple the index page and template files are in this application! As a coder, you would have full control over logical execution of code on the index page and all background class files.
The only unknowns would be if your designer mucks with your smarty tags in the template files, but that won’t be happening, now, will it?

Download: code_sample23.zip

Comment and Contribute

Your comment has been submitted and is pending approval.

Author:

Ben Robinson

Comment:



Comment: