Smarty

5 June, 2008 at 23:12 7 comments

This article is intended for PHP programmers and HTML designers interested in applying a new technique for web development – PHP templating. Advanced knowledge of PHP programming and HTML is assumed.

Smarty Overview

The theoretical web development process is that: first the designer makes the interface, and breaks it down into HTML pieces for the programmer then the programmer implements the PHP business logic into the HTML.

That’s fine in theory, but in practice, from my experience, the client frequently comes with more requirements, or maybe more modifications to the design or to the business logic. When this happens , the HTML is modified (or words rebuilt ) programmer changes the code inside HTML.

The problem with this scenario is that the programmer needs to be on stand-by until the designer completes the layout and the HTML files. Another problem is that if there is a major design change then the programmer will change the code to fit in the new page. And that’s why I recommand Smarty. Smarty is a templating engine for PHP.

You can download it from http://www.phpinsider.com/php/code/Smarty/ or http://smarty.php.net . The installation process is very simple. Just read the documentation and follow up the instructions.

So what is Smarty ? Smarty is a set of PHP classes that compile the templates into PHP scripts. Smarty is a template language and a very useful tool for designers and programmers.

Smarty for Designers

Designers work with HTML files. To work with Smarty, you work with template files. These files are are made up of static content but combined with Smarty mark-up tags. All the template files have a .tpl extension. The Smarty template tags are enclosed within { and } delimiters.

Let’s consider the basic structure of a web page. There is a header, a middle part, and a footer. A template file that includes the header and the footer looks like this:

{include file="header.tpl"}
<form name="form1">
Label1 <input type="text" name="text1">
<input type="submit" value="submit">
</form>
{include
file="footer.tpl"}

All the templates should reside in a single template directory. After calling a template for the first time, the compiled template will reside in templates_c.

Smarty language is very poweful. All the variables that come from PHP are identified in Smarty with {$Variable_Name} (we precede them with a $ sign). So if we have a variable in PHP that is called $MyName, then to print it in Smarty you have to write something like:

<html>
<
body>
Welcome, {$MyName} <br>
</
body>
</
html>

The power of Smarty lies also in its flexibility. You can insert IFs and LOOPs into the template. The syntax for IF is:

{if <condition> }
html code
{else}
html code
{/if}

Let’s say you have a dynamic menu based on links. Depending on the link you click, you go to a specific page. So you get from PHP a variable $Menu with a integer value, depending on the page you are. The template looks like :

{if ($Menu == 1) }
Option 1
{else}
<
a href="option1.php">Option 1</a>
{/if}
{if (
$Menu == 2)}
Option 2
{else}
<
a href="option2.php">Option 2</a>
{/if}

For coding a loop let’s suppose you get an array like the following from PHP :

<table>
<
tr
{section name=user loop=$userID}
{if
$smarty.section.user.iteration is odd}
bgcolor=#efefef
{else}
bgcolor=#ffffff
{/if}
>
<
td> ID = {$userID[user]} </td>
<
td> Name = {$name[user]} </td>
<
td> Address = {$address[user]} </td>
</
tr>
{
sectionelse}
<
tr>
<
td>
There is no user.
</
td>
</
tr>
</
section>
</
table>

Iteration is an internal counter for Smarty. It helps us to know the current iteration of the section. I use this internal variable to make alternate row colors in the table by checking if current iteration value is odd or not (Note that iteration was added to Smarty from version 1.4.4).

An alternative for LOOPS is FOREACH which is used to loop over a single associative array.

<foreach from=$users item=current_user>
Name = {$current_user}
<
foreachelse}
No user available.
</foreach>

The main difference between SECTION and FOREACH is that for SECTION you can start from a specific value, and can also set a step for the iteration, whereas for FOREACH you have to loop over all values.

Smarty for Programmers

The advantage for programmers is that they write the code in a PHP file without having to mix the instructions with HTML. Furthermore, if the designer changes the layout of a page the programmer doesn’t have to change the code to suit the new layout since the functionalities won’t change. You do your work in your files, assign to the templates all the values needed to print on the site and go out for a beer. You won’t get phone calls asking you to change a bit of code because the designer changed the layout and now a set of internal errors cropped up.

In the PHP file you need to include the Smarty class require ‘Smarty.class.php'. After that you need to instantiate the smarty with $smarty = new Smarty.

To assign a variable to the template you need to $smarty->assign('UserName', ‘John Doe’). After everything is finished you call the method to display the template $smarty->display('index.tpl').

A sample code looks like this (index.php) :

<?php
require 'Smarty.class.php';
$smarty = new Smarty;

$smarty->assign(‘Username’, ‘John Doe’);
$smarty->display(‘index.tpl’);
?>

The template (index.tpl) looks like this:

<html>
<
body>
Welcome {$Username}
</
body>
</
html>

You can also create an array in PHP an pass it to the template:

$tmp = array ( 'UID'=> '10', &'Name' => 'John Doe', 'Address'=>'Home address');
$smarty->assign('info', $tmp);

Sample Script

This script connects to a local database and select all the products from the ‘Products’ table. Then it passes all the values to the template, which prints them on the screen.

INDEX.PHP

<?php
require 'Smarty.class.php';
$smarty = new Smarty;

$hostname = “localhost”;
$dbUser = “sqluser”;
$dbPass = “sqlpass”;
$dbName = “sqldb”;
// connect to the database
$conn = mysql_connect($hostname, $dbUser, $dbPass) or die(“Cannot connect to the database”);

mysql_select_db($dbName);

$sql = “SELECT prodID, info FROM products ORDER BY prodID ASC”;
// get all the products from the table
$res = mysql_query($sql);
$results = array();
$i=0;
while (
$r=mysql_fetch_array($res)) {
$tmp = array(
‘prodID’ => $r[‘prodID’],
‘info’=> $r[‘info’]
);
$results[$i++] = $tmp;
}
// pass the results to the template
$smarty->assign(‘results’, $results);
// load the template
$smarty->display(‘index.tpl’);
?>

INDEX.TPL

<html>
<
body>
Here's a table with the results: <br>
<table cellpadding=1 cellspacing=0 border=0 width=100%>
{section name=nr loop=$results}
<tr {if $smarty.section.nr.iteration is odd} bgcolor="#efefef"{/if}>
<td class=fb width=15%>
<nobr><a href=”show-product.php?id={$results[nr].prodID}">Press here</a>

<td class=fb width=29%><a href=”show.php?id={$results[nr].prodID}”
{popup inarray=$smarty.section.nr.iteration}
>{$results[nr].info}</a></td>
</tr>

{sectionelse}
<tr><td align=”center”><br><b>no product </b> <br> </td></tr>
{/section}

</table>

<br>

Here’s a select with the results: <br>
<select name=”mys”>
{section name=nr loop=$results}
<option value=”{$results[nr].prodID}”>{$results[nr].info}</option>
{/section}
</select>

</body>
</html>

[http://devzone.zend.com/article/1238-PHP-Templating-with-Smarty]
Advertisements

Entry filed under: PHP, XHTML, XML. Tags: , .

Web Applications and OSGi (Costin Leau) BeContent – A meta-framework for web applications

7 Comments Add your own

  • 1. Suresh Kumar  |  7 June, 2008 at 22:06

    Nice Tutorial. I suppose to implement a website using Smarty Template. I am searching for Some tutorials. Thanks for Providing some Valuable information.

    I appreciate your good work

    Reply
  • 2. Maurizio Storani  |  9 June, 2008 at 13:44

    Thank’s Kumar
    I have used Smarty so many times but not in this site 😉

    I ‘am working on a Smaj (Smarty-Ajax), it’s a new tecnology that merge a kind of Smarty tecn. and Ajax language, beta relase will be ready for December, I hope.

    Stay tuned

    Bye
    Maurizio

    Reply
  • 3. Cevarief  |  28 June, 2008 at 04:06

    I never user smarty as i do design and coding. Using pure php is much more convenient for me over using smarty templating.

    Reply
  • 4. Maurizio Storani  |  28 June, 2008 at 10:15

    HI Cevarief

    SMARTY is a hight abstraction for facility design and coding.

    Of course SMARTY is not a panacea, but you can implement a MVC pattern easily for example.

    Mainly with SMARTY you avoid mix PHP and HTML code, so developer, designer and graphic designer can work concurrently.

    Reply
  • 5. BuyLevitra  |  10 July, 2008 at 23:45

    Hello! Personally I fully agree with recent comments.

    Reply
  • 6. hopeson  |  25 July, 2008 at 05:53

    I want to do something like this.

    If user ID is 5,6 and 7 then display the text.

    You have permissions.

    else display

    You do not have permissions.

    where my field name in database is UID

    pretty n00b question 😦

    Reply
  • 7. Maurizio Storani  |  25 July, 2008 at 08:49

    Hi

    It’s enough simple and you can resolve it with simple php code.

    I have to know other things for solve it in the best manner, but you can resolve it in this way:


    if($container_value['UID']>=5 && $container_value['ID']<=7)
    //samething
    else
    //samething

    Make $container_value an associative array using fetch_assoc() function.

    HTH
    Maurizio

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Trackback this post  |  Subscribe to the comments via RSS Feed


IT Passion’s Store

Archives

Communities

Get the Source
OSGi supporter
JUG Milano

Upcoming Events



....

Blog Stats

  • 348,048 hits

My PageRank

What's My Google PageRank?

%d bloggers like this: