Issuu on Google+

Smarty for Beginners by Hermawan Haryanto 2003-12-28

Synopsis Join Hermawan as he shows you the basic of the Smarty templating system.

Page 1

Smarty for Beginners by Hermawan Haryanto

Preface With this tutorial I aim to explain how to use the ( Smarty Template Engine in the simplest terms so even beginning coders of PHP can understand how to use it as their primary template engine. By reading this tutorial I presume that all of you have the idea of what Smarty can do for you and how it is an amazing template engine which has speed, portability and stability.

Getting Started The first thing you need to do is download the distribution from the ( download section on its official site. Save it on your computer then unzip it somewhere in your harddrive. There is a folder named "libs" on your extracted files. Upload that "libs" folder on your webhosting account and rename it as "smarty". Next, create a sub folder on your web directory; let's say your created subfolder is "smartyrules", so now you can access that folder using your browser by typing this address Inside that folder you should create another two subfolders, called "html" and "compile". I'll explain to you later why this is necessary. If you use a *nix distribution then you need to CHMOD 777 to the folder "compile", but if you use Windows then you won't need to do that.

File Creation Let's go back to "smartyrules" folder. In that folder, create a new PHP file with the contents of as follows: <?php # Filename: # the exact path is defined. $fixpath = dirname(__FILE__); # changes this value according to your uploaded smarty distribution. # don't forget to add trailing back slash # change 'username' to your username on web hosting account define ("SMARTY_DIR", "/home/username/smarty/"); require_once (SMARTY_DIR."Smarty.class.php"); $smarty = new Smarty; $smarty->compile_dir = "$fixpath/compile"; $smarty->template_dir = "$fixpath/html"; ?>

Page 2

Smarty for Beginners by Hermawan Haryanto

Save the file as Create another new PHP file, the contents as follows: <?php # filename: index.php require_once ("./"); $smarty->display ("index.html"); ?>

Save the file as index.php Go to "html" directory in the "smartyrules" subfolder. Create a new html file, the contents as follows: <html> <head> <title>My First Smarty Page</title> </head> <body> This is my First Smarty Page </body> </html>

Save the file as index.html All set, now you can open your browser and type your address You'll see your page is generated using index.html in subfolder "html" as the template. That would your first Smarty page. What Smarty does is compile index.html and put it in the "compile" folder then display it right away from there. You can see in the "compile" folder, there are new files, they were created by Smarty.

The Basics The basic operation of a template engine is to assign variables or arrays and integrate them with your html page. Let's try something simple first. Open your index.php page and add this line before the $smarty->display function. $smarty->assign ("name", "Hermawan Haryanto");

Open your index.html page and add this line: My name is {$name}

Page 3

Smarty for Beginners by Hermawan Haryanto

The result would be: My name is Hermawan Haryanto

Now, let's try assigning arrays to your template. Add these lines in index.php remembering all added lines would be before the $smarty->display function. $friends = array("Mike", "Simpson", "Bill", "Torvald", "Paul", "John Doe"); $smarty->assign ("friends", $friends);

Open your index.html page and add these lines: Friends List: {section name=i loop=$friends} {$friends[i]}<br> {/section}

You'll see the array is pulled and populated on the html page.

What about accessing a database? Nice question. I'll try to explain it in here. First you need to know your database configuration such as username, password and your database name. If you have them already, then you can create your table using your Database Administration tools. I prefer using phpMyAdmin, you get the latest version of it at ( Create your table using this query: CREATE TABLE `friends` ( `friends_id` int(10) unsigned NOT NULL auto_increment, `friends_name` varchar(255) default NULL, UNIQUE KEY `friends_id` (`friends_id`) ) TYPE=MyISAM; INSERT INTO `friends` VALUES (1, 'Paul'); INSERT INTO `friends` VALUES (2, 'Matt'); INSERT INTO `friends` VALUES (3, 'John'); INSERT INTO `friends` VALUES (4, 'Mike'); INSERT INTO `friends` VALUES (5, 'Rendi'); INSERT INTO `friends` VALUES (6, 'Pailul');

Open your index.php file and add these lines:

Page 4

Smarty for Beginners by Hermawan Haryanto

$db_host = "localhost"; $db_user = "database_user"; $db_pass = "database_pass"; $db_data = "database"; $conn = mysql_connect ($db_host, $db_user, $db_pass) OR DIE ("Can't connect to database"); @mysql_select_db ($db_data, $conn); $query = "SELECT * FROM friends"; $result = mysql_query ($query, $conn); if (mysql_num_rows ($result) >= 1) { $friends = array(); while ($rows = mysql_fetch_array ($result, MYSQL_ASSOC)) array_push ($friends, $rows); $smarty->assign ("friends", $friends); } Open your index.html page and add these lines: Friends List: {section name=i loop=$friends} {$friends[i].friends_name}<br> {/section}

Now you'll see the list of friends on your page. You can do some other formatting such as nl2br, truncate, upper, or lower directly from html template page, not from your script. That is why we use Smarty, to separate between business logic and presentation logic. The script should only work to pull data from db but not to format the result. The formatting of the result is done in the html page.

Some fun stuff Open your index.html file again and let's add some fun stuff. We will use some Smarty predefined variables. Add this line: {$|date_format:"%Y-%m-%d %H:%M:%S"}

Refresh your browser and you'll see today's date and time on the server. The formatting is done using strftime(). Add this line: {$smarty.server.PHP_SELF}

Page 5

Smarty for Beginners by Hermawan Haryanto

Refresh your browser and you'll see the filename you are accessing now. I guess the file would be "/smartyrules/index.php". Let me know if it's something else :). You can read all of this stuff in the Smarty manual. There are plenty of Smarty predefined variables you can adapt and use on your pages. That's all for now, I'll be back with another tutorial soon. All questions and suggestions are welcome.

About the Author Hermawan Haryanto is a Senior Programmer of a Web Development Company in Las Vegas. Handling programming services world wide and writing articles and tutorials since 1996. Authoring ( with his wife. Visit ( his homepage and you can contact him through hermawan at codewalkers dot com.

Page 6