Smarty has build in loop functions to minimise the use of PHP Code from within your template documents. In this tutorial I am going to show you how to create a simple page To output an array using a loop in Smarty. The array will be outputted in a simple HTML Table to show how smarty works.
Ok So we need the smarty Libs to do this you can retreive the latest smarty distribution from Smarty : Template Engine
Once you have downloaded it Upload it onto your web server or put it in your WAMPP/LAMPP htdocs directory.
On your server create 2 new folders with the following configuration.
Dir Name CHMOD ----------------------------------- html 665 cache 777
Ok now create a new file and call it config.php and place the follwoing code into the file
<?php
$dir = dirname(__FILE__); //Just to get the directory we are in
define ("SMARTY_DIR", "<WHERE YOU STORE SMARTY>"); //Use an Absolute path (/home/<user>/htdocs/smarty on linux)
require_once (SMARTY_DIR . "Smarty.class.php");
$smarty = new Smarty;
$smarty->compile_dir = "$dir/cache";
$smarty->template_dir = "$dir/html";
?>
Now we have our basic smarty config setup we are ready to use smarty to output some data.
Create a new file call it index.php this is where our aarray is gonna be and It will call out template file.
<?php
require_once ("./config.php");
$phpGods = array("Affix","Jordan","CodeCall");
$smarty->assign("gods", $phpGods); //Here we assign the Array to a smarty var
$smarty->display ("array.tpl"); //This will display the file array.tpl from our html directory
?>
Now in the HTML Direcotry we need to create our array.tpl file. To do this make a new HTML file and save it as array.tpl in the html directory.
In this file use the following code.
<h1>PHP Gurus</h1>
<div align="center"><table width="50%" height="50%>
{section name=i loop=$gods}
<tr>
<td>{$gods[i]}</td>
<tr>
{/section}
</table></div>
Now we have this done Upload your script and test it.
You will notice the loop I created using smarty. This is basically a for each loop from PHP.
Now you know the basics of smartyPHP hope you enjoyed my tutorial and will stop including HTML in your PHP Scripts :D
any questions email me : affix@fedoraproject.org


Sign In
Create Account


Back to top









