SMARTY Template For PHP

Smarty Template(s) With PHP

The Smarty Template engine is a library that PHP programmers can use so that they can separate logic from design. This quick Smarty tutorial should help minimize the confusion while you try to grasp the methods for using Smarty.

Why Separate Logic From Design?

Although separating logic from design has many benefits, one of the main benefits is that a project or page can be split between different individuals. In a workplace setting, you often have a front end web developer or web designer that will alter the 'look' of the website. Therefore, it makes that person's job easier if he only edits and tests the design and avoids any data between Smarty's {} tags.

Meanwhile, the web developer will write and alter the code that is displayed in the logic file with the '.php' extension. Now, both can do their work at the same time without worrying about who is working on the file. Obviously, if both the heavy lifting backend developer and front end designer need to use the same file, there could be issues like overwriting and losing work. Simply speaking, two people on one file is not efficient, especially is both people want to work on it at the same time.

Asides from Smarty being convenient and friendly between logical and design users, it can also help maintain control of an application from a temporary front end web designer. For example, if you plan to work primarily as a web developer and outsource the design to a stranger or part time worker, you may not want the designer to have access to all the logical code and heart of the page. This way, the designer's code is rather useless for other projects based on the current scripting.

All in all, the outsourced individual could not sabotage or steal a project; especially if he only has write access or an upload privilege on the exact design files you had contracted him to work on.

Since the spiel mentioned above explains why Smarty is beneficial, you may already be thinking when using Smarty could be overkill. Essentially, if one individual will be creating and maintaining a small PHP project, it could be much quicker to use only one file for the logic and presentation. At this point, it could be a matter of preference since one person may like minimize the files while another would like to work with two smaller files with the logic in one file and the presentation in the other file.

The Basics

To make this sound easy, I will try to explain a traditional PHP file vs using a Smarty template. A PHP file allows you to code PHP, HTML, CSS, javascript, Jquery all in one file that has the '.php' extension.

Smarty, on the other hand, is used with a pair of files; a '.php' file which includes the Smarty library and PHP coding and a matching '.tpl' file which contains the html(and other coding like Jquery).

To keep things simple, the '.php' and '.tpl' files can have a matching name so it is easy to know which files belong to which without having to find the line that references the '.tpl' file within the '.php' file. Make sense? The '.tpl' file that is used and compiled is done with the $smarty->display() method. For example, the logical PHP file called filename.php could use the filename.tpl file for output.

 $smarty->display("filename.tpl");


Getting Started

To be able to use Smarty, you follow a few steps.

1) Download and unzip the file from Smarty.net.
2) Moves the files into your root folder or somewhere else on your server and write the path in your .php.ini file or in your files which will use Smarty.

The first method can be done in less than a minute. All you need to do is extract the download and move the libs folder into the location where you will create your working files. Often, this is in the public_html or example.com folder. The second method can keep the library in a more secure place; such as the /usr/local/lib/php folder.

The second method also allows all hosted domain names to have access to the library which eliminates redundant installations. The example below shows how to setup Smarty on Linux so all domains can use it.

 root# cd /usr/local/lib/php root# wget smarty.net/files/Smarty-3.1.18.tar.gz root# tar xvfz Smarty-3.1.18.tar.gz root# cp -r Smarty-3.1.18/libs/* /usr/local/lib/php/smarty root# rm -R Smarty-3.1.18

3) Create a .php file and instantiate the Smarty object.

require_once("libs/smarty.class.php"); 
$smarty = new Smarty ();

If you plan to access Smarty from /usr/local/lib/php/Smarty you will need to add an extra line into the '.php' file to create a constant that points to the path and you need to alter the require_once() function so it access the Smarty class from the adequate directory.

define('SMARTY_DIR', '/usr/local/lib/php/smarty/'); require_once(SMARTY_DIR . 'Smarty.class.php'); 
$smarty = new Smarty ();

Alternatively, you could also use the simple coding shown below.

require_once('/usr/local/lib/php/smarty/'); 
$smarty = new Smarty ();


Beyond The File Pairing

When the PHP file is requested in the browser, the '.tpl' file is compiled and output. Although they are two different files, the key to working with them is to remember that all variables in the '.php' file can be assigned and passed into the '.tpl' file. In addition to that, you should note that any code passed into the '.tpl' can be interpreted with... let's say Smarty coding. I will make a quick list below which shows how some php code from the '.php' file can be interpreted with the '.tpl' file.

Setting a Variable With Logic and Output To Presentation

Variable (index.php)

$my_string = "Here is my string."; 
$smarty->assign("my_string",$my_string);

Variable Output (index.tpl)

 <p>{$my_string}</p>


Where To Go From Here

From the simple examples shown above, you can now use Smarty and display simple variables in the presentation file which contains the '.tpl' extension. If I could sum up how to use Smarty from here on, I will attempt to do so in 1 sentence.

Variables, loops, objects and functions can be used within the '.tpl' file with special syntax; often nested within curly{} brackets. I will attempt to elaborate on the one-liner. If you made an array called $myarray within the '.php' file, you could run it through a foreach loop within the '.tpl' file.


Foreach Loop (index.tpl)

{foreach item=myitem from=$myarray} 
<p> {$myitem} </p> 
{/foreach}

Calling a Function

The example below shows how to call a function and return a value. Functions called with the '.tpl' are not cached. For simple practice, doing all logic code in the '.php' file and only outputting in the '.tpl' files makes using Smarty very simple and organized.
Functions file (my_functions.php)

function smarty_insert_my_function() 
{ 
return "This is returned from the function"; 
}


index.tpl

 {insert name="my_function" assign="my_returned_value" script="my_functions.php"} <p>{$my_returned_value}</p> </body>

Built-in PHP Functions

Smarty allows you to use built-in functions within the '.tpl' file. There are many so I will not go into the details. But, I will show an eaxmple of the '.php file and '.tpl' file changing the string to lower case letters.

 .php $string = "AbCdE"; $string = strtolower($string); //ouputs abcde
 .tpl {$string|lower}

More examples can be found at http://www.smarty.net/docs/en/language.modifiers.tpl

Extras To Get You Going

Two important factors worthy of consideration when using Smarty are its built-in functions. Although there are many, two which deserve utmost attention are {php} and {literal}.

The PHP tags {PHP}{/PHP} allows you to write good, old PHP within a the '.tpl' file, while code within {literal}{/literal} will not be translated and that allows you to write plain, old HTML, Javascript and CSS within these tags. More important functions can be found at http://www.smarty.net/docs/en/language.function.php.tpl.

More Examples

The tutorial above can be used as a simple cheatsheet for using Smarty. The next set of examples are more tutorials regarding its usage.

1. Different Arrays and Foreach Loops With Smarty
2. Custom Smarty Header and Footer Files
3. Using PHP Inside ".tpl" file
4. Using CSS and Javascript Within TPL Files Using Literal tags
5. Smarty Forms and Elements
6. Object Oriented Programming With Smarty
7. Smarty Limiting File Access
8. Smarty Template Configuration Files
9. Using Functions
10. Include Files