PHP the Smarty Way
What is Smarty? It’s a php templating engine. I’ve used Smarty on several projects and I like it’s simplicity. It forced me to keep my application logic separated from the presentation code. This is a must when organizing your code. The last thing you want is your designer browsing through hundreds of lines of code just to apply some html. Furthermore, Smarty comes with extra features such as built-in caching, vairable modifiers, filters, and much more including user contributed plugins.
How to install Smarty
Installing Smarty is a fairly simple process. I will break the installation process into 3 steps.
STEP 1 - Download and Extract
Grab the latest Smarty release from Smarty’s download section then extract the package into your application directory. Now rename the new directory created by the archive from “Smarty-x.x.x” to “smarty” for the sake of simplicity.
STEP 2 - Create required folders
Smarty requires some folders for caching purposes among other things. In your smarty directory create the following folders:
/path/to/application/smarty/cache
/path/to/application/smarty/configs
/path/to/application/smarty/templates
/path/to/application/smarty/templates_c
Then change the permissions of the newly created cache and templates_c folders to 755
STEP 3 - Create the smarty setup file
Create a file called smarty.php and put this wherever your application configuration folder is located. You’ll want to include this file in your application php files. So if you use a global index.php file or configuration file include it in there.
Here’s the following setup code for smarty.php
// put full path to Smarty.class.php require('/path/to/application/smarty/libs/Smarty.class.php'); $smarty = new Smarty(); $smarty->template_dir = '/path/to/application/smarty/templates'; $smarty->compile_dir = '//path/to/application/smarty/templates_c'; $smarty->cache_dir = '/path/to/application/smarty/cache'; $smarty->config_dir = '/path/to/application/smarty/configs';
That’s it. Now whenever you want to display a template file, you’ll need to create that file in your templates folder (ie: /path/to/application/smarty/templates/index.tpl) and then you would call this template from your php file with the following code
$smarty->assign('title', 'Hello World'); // creates a variable 'title' with the string "Hello World" in your template file $smarty->display('index.tpl');
In your template file you can access the title variable using the following syntax: {$title}
This is a fairly simple way to get started with Smarty.
Here is a crash course on using this engine from the Smarty website - Smarty Crash Course
If you’re already familiar with Smarty, here’s a handy cheat sheet from somewherein.
One last thing. If you’re a CakePHP user I don’t really recommend using Smarty because CakePHP’s template system is much more convenient, nonetheless, there is a way integrate Smarty with CakePHP. Read the article at the bakery.