An explanation of Smarty template engine

in Misc no responses

Considering that there are so many web applications and software using the smarty template engine; and that one of those pieces of software is Flatpress, I thought it would be a good idea to write a bit about smarty.

What is it?

The clue is in the name; it’s a template engine. What this means is that smarty is used to display the output of processed data and does not do the processing itself; even thought Smarty is able to do a small amount of processing.

Smarty divides the structure of a web application cleanly into two phases; Processing and output. This is how the application would be divided.

PHP SCRPIT  (PROCESSING) > TPL FILE (THE DESIGN) > OUTPUT HTML (WHAT THE BROWSER SEES)

Why use it?

There are various reasons why smarty should be used to handle the presentation of a site. Here are a few.

It’s clean – The combination of PHP and HTML can look very messy. Why would anyone want all those pieces of PHP code in with the presentation layer of your website, when all the processing can be done via PHP and then have the output displayed with a simple tag?

It has Add-ons – Add-ons are available to help speed up development. Examples of these are Pagination, Form Validation, Drop Down Menus, Calendar Date Pickers, etc.

It’s fast – Smarty has a huge set of features, but this does not impede the performance of the engine. Smarty has built in caching capabilities that can be used to make the presentation of the site load much faster. Though most of the time this is not needed.

For more features: http://www.smarty.net/rightforme.php

Examples

Here is a simple example of how smarty can be used:

PHP

include('Smarty.class.php');
// create object
$smarty = new Smarty;

// assign some content. This would typically come from
// a database or other source, but we'll use static
// values for the purpose of this example.
$smarty->assign('name', 'george smith');
$smarty->assign('address', '45th & Harris');
// display it
$smarty->display('index.tpl');

TPL File

<html>
<head>
<title>User Info</title>
</head>
<body>
User Information:<br />
Name: {$name}<br />
Address: {$address}<br />
</body>
</html>

Output HTML

<html>
<head>
<title>User Info</title>
</head>
<body>
User Information:<br />
Name: george smith<br />
Address: 45th & Harris<br />
</body>
</html>

View more examples: http://www.smarty.net/crashcourse.php

 
comments

No Comments Yet

 

Have something to say?