Smarty: A closer look

Intended Audience
Overview
How it works
Extending Smarty with Wrapper Classes
Template Caching with Smarty
Securing Smarty
Template Configuration Files

Data Manipulation within Templates
Summary
About the Author

Intended Audience


This article is intended for PHP programmers and HTML designers wishing to utilize
the more advanced features of the Smarty templating engine. A working knowledge
of PHP, PHP’s OOP structure, and HTML is assumed. This article also assumes
the reader has read Cezar Floroiu’s introductory article PHP
Templating with Smarty
and has a working Smarty setup.

Overview


At its most basic, Smarty allows programmers to unchain themselves from the design
process, a long standing dream of many. However, Smarty also has many advanced
features that you may have been missing out on.

This article will demonstrate some of the more complex features in Smarty such
as security features, template caching, and extending Smarty with wrapper classes.
This article will show HTML designers how to extend their templates with configuration
files and built-in data manipulation functions.

How it works


Extending Smarty with Wrapper Classes


By default Smarty looks for templates in the directory in which it is called.
Often this isn’t feasible within your site’s directory structure since, for security
reasons, templates should not be placed in a web accessible directory. In order
to change Smarty’s default behavior you need to create a wrapper class (that is
actually a child class of the Smarty class).


<?php

// Define our template directories

define('TEMPLATE_DIR','/usr/share/templates');

define('COMPILE_DIR','/usr/share/templates/templates_c');

define('CONFIG_DIR','/usr/share/templates/configs');

define('CACHE_DIR','/usr/share/templates/cache');

// Create a wrapper class extended from Smarty

class Page extends Smarty 

{

  
// $cache and $cache_lifetime are the two main variables

  // that control caching within Smarty

  
function Page($cache true$cache_lifetime 300)

  {

    
// Run Smarty's constructor

    
$this->Smarty();

    // Change the default template directories

    
$this->template_dir TEMPLATE_DIR;

    
$this->compile_dir COMPILE_DIR;

    $this->config_dir CONFIG_DIR;

    
$this->cache_dir CACHE_DIR;

    // Change default caching behavior

    
$this->caching $cache;

    $this->cache_lifetime $cache_lifetime;

  }

}

$page = new Page();

$page->assign('foo','bar');

$page->display('foo.tpl');

?>

Template Caching with Smarty


In the above code you’ll notice Smarty::caching and Smarty::cache_lifetime

are set with default values. Smarty does not enable caching by default, but by
turning it on you increase the speed with which Smarty is able to process requests
for templates.

By default our Page class sets the lifetime of our cache to 5 minutes. It is important
to note this while doing development on your code. If you tweak the output or
your designer makes changes to the template Smarty will not reflect those changes
for 5 minutes unless you do one of two things: set Smarty::cache_lifetime
to 0 or set Smarty::force_compile to TRUE. (Setting
Smarty::force_compile to TRUE makes Smarty regenerate
the template each time the script is called. The Smarty documentation says this
should only be used for development and debugging and should not be used in a
production environment.)

Securing Smarty


By default Smarty allows PHP code to be run within templates using {php}{/php}
tags. This may, or may not, be a good idea. In my experience it is better to limit
the control given to designers. Random PHP code inserted into your page could
interfere with the desired effects of the application or even break the application
altogether.

To disable the use of PHP within your Smarty templates, set
Smarty::php_handling to
SMARTY_PHP_REMOVE in your wrapper class
constructor.

Enabling Smarty’s security feature, which by default is set to FALSE,
makes Smarty run in a sort of safe mode. This is desirable if you have untrusted
parties editing the templates, such as those accessing the templates via FTP.
To enable this feature set Smarty::security to TRUE

in your wrapper class’ constructor.

Template Configuration Files


Configuration files are a great way for template designers to set global variables,
such as common colors, to be used across many templates.


# Sample configuration file

# Pound signs are used for comments

colorA #cccccc

colorB #eeeeee

title "My Homepage"

[Login]

title "Login to My Account"

titleColor #000000

In the above example you’ll notice the top part
does not include a section, this is because these are global variables. These
variables will be loaded every time the configuration file is loaded. (In the
event of a section’s variable name conflicting with a global variable
name, the section’s variable is used.)

To use your newly created configuration file you will need to use the {config_load}
function.


{config_load file="config.conf"}

<
html>

<
title>{#title#}</title>

<body bgcolor="{#colorA#}">

  
Your template stuff goes here.

</
body>

</
html>


You can alternatively load just a section of the configuration file by using the
section parameter.


{config_load file="config.conf" section="Login"}

<html>

<
title>{#title#}</title>

<body bgcolor="{#colorA#}">

  
Your template stuff goes here.

</body>

</
html>

In the above example the {#title#} variable would output “Login to
My Account” while {#colorA} would remain #cccccc.

Data Manipulation within Templates


Smarty includes a decent array of variable modifiers, including various string
manipulations and date formatting. For a complete listing of the variable modifiers
you will want to check out http://smarty.php.net/manual/en/language.modifiers.php.
Developers might be interested in creating their own modifiers, and Smarty supports
this. For more information on creating your own modifiers, filters, and plugins,
check out http://smarty.php.net/manual/en/plugins.php.

Let’s first take a look at date formatting. Many programmers store dates in nonreadable
formats, such as UNIX timestamps. Smarty’s built in date_format function accepts
any time format parsable by PHP’s strftime() function.

{$smarty.now|date_format:"%m-%d-%Y"}

{
$smarty.now|date_format:"%A %B, %e %Y"}


The above would output “02-10-2003″ and
“Monday February, 10 2003″ respectively.

Other modifiers of note include upper, capitalize, and truncate. Upper
is equivalent to PHP’s strtoupper() function, capitalize
is similar to PHP’s ucwords(), while truncate simply
takes the variable and limits it to a given number of characters.

Summary


Smarty has many advanced features that allow programmers to increase the efficiency
of their applications. Smarty also has many complex template features to give
designers more refined control over the formatting of the template data.

Maybe Smarty is the answer to the long running standoff between programmers wanting
to keep control of their applications and designers needing refined control over
the output of those applications.

About the Author


Joe Stump is currently in his last semester at Eastern Michigan University. He
has worked on many large PHP driven sites and does freelance web development in
his free time. He recently started a consulting company called Jerum (http://www.jerum.com),
which takes up much of his free time. You can contact him directly at joe@joestump.net.

Published: March 18th, 2003 at 12:00
Categories: Uncategorized
Tags: ,