smarty

6

Click here to load reader

Upload: vinay-kr-sharma

Post on 07-Mar-2016

216 views

Category:

Documents


0 download

DESCRIPTION

by Hermawan Haryanto Page 1http://codewalkers.com/tutorials/56/1.html 2003-12-28 Join Hermawan as he shows you the basic of the Smarty templating system.

TRANSCRIPT

Page 1: Smarty

Page 1http://codewalkers.com/tutorials/56/1.html

Smarty for Beginnersby Hermawan Haryanto

2003-12-28

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

Page 2: Smarty

Smarty for Beginners

by Hermawan Haryanto

Page 2http://codewalkers.com/tutorials/56/1.html

PrefaceWith this tutorial I aim to explain how to use the (http://smarty.php.net/) SmartyTemplate Engine in the simplest terms so even beginning coders of PHP canunderstand 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 dofor you and how it is an amazing template engine which has speed, portability andstability.

Getting StartedThe first thing you need to do is download the distribution from the(http://smarty.php.net/download.php) download section on its official site. Save it onyour 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 andrename 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 thisaddress http://www.domain.com/smartyrules.

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 distributionthen you need to CHMOD 777 to the folder "compile", but if you use Windows then youwon't need to do that.

File CreationLet's go back to "smartyrules" folder. In that folder, create a new PHP file with thecontents of as follows:

<?php # Filename: libs.inc.php

# 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 3: Smarty

Smarty for Beginners

by Hermawan Haryanto

Page 3http://codewalkers.com/tutorials/56/1.html

Save the file as libs.inc.php.

Create another new PHP file, the contents as follows:

<?php # filename: index.php require_once ("./libs.inc.php"); $smarty->display ("index.html");?>

Save the file as index.php

Go to "html" directory in the "smartyrules" subfolder. Create a new html file, thecontents 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 addresshttp://www.domain.com/smartyrules. You'll see your page is generated usingindex.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 itright away from there. You can see in the "compile" folder, there are new files, theywere created by Smarty.

The BasicsThe basic operation of a template engine is to assign variables or arrays and integratethem 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 4: Smarty

Smarty for Beginners

by Hermawan Haryanto

Page 4http://codewalkers.com/tutorials/56/1.html

The result would be:

My name is Hermawan Haryanto

Now, let's try assigning arrays to your template. Add these lines in index.phpremembering all added lines would be before the $smarty->display function.

$friends = array("Mike", "Simpson", "Bill", "Torvald", "Paul", "JohnDoe");$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 databaseconfiguration such as username, password and your database name. If you have themalready, then you can create your table using your Database Administration tools. Iprefer using phpMyAdmin, you get the latest version of it at (http://phpmyadmin.net/)http://phpmyadmin.net.

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 5: Smarty

Smarty for Beginners

by Hermawan Haryanto

Page 5http://codewalkers.com/tutorials/56/1.html

$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 todatabase");@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 suchas nl2br, truncate, upper, or lower directly from html template page, not from yourscript. That is why we use Smarty, to separate between business logic andpresentation logic. The script should only work to pull data from db but not to formatthe result. The formatting of the result is done in the html page.

Some fun stuffOpen your index.html file again and let's add some fun stuff. We will use some Smartypredefined variables.

Add this line:

{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"}

Refresh your browser and you'll see today's date and time on the server. Theformatting is done using strftime().

Add this line:

{$smarty.server.PHP_SELF}

Page 6: Smarty

Smarty for Beginners

by Hermawan Haryanto

Page 6http://codewalkers.com/tutorials/56/1.html

Refresh your browser and you'll see the filename you are accessing now. I guess thefile 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 Smartypredefined variables you can adapt and use on your pages. That's all for now, I'll beback with another tutorial soon. All questions and suggestions are welcome.

About the AuthorHermawan Haryanto is a Senior Programmer of a Web Development Company in LasVegas. Handling programming services world wide and writing articles and tutorialssince 1996. Authoring (http://dekap.com/) dEkap.com with his wife. Visit(http://hermawan.com/) his homepage and you can contact him through hermawan atcodewalkers dot com.