|
Ok smarty
is now usable with your files.
To be able to display templates you'll need to include this line on all
of your files:
require_once ("./templates/libs.inc.php");
To display
a smarty file, use the following code:
$smarty->display("myfile.html");
Thats it, you've set up your template system. Now I'll go into
more detail about some of the functions smarty offers.
Variables
To assign a variable for smarty to read:
$smarty->assign("message", "Hello");
The first parameter is the name the variable will
be when passed to smarty, the second is the value of that variable.
To call a variable from a smarty file you use {$variablename} so our message
variable would be {$message}.
Loops/Arrays
In a file,
create an array and assign it to smarty:
$names
= array("john", "joe", "eric", "matt");
$smarty->assign("names",
$names);
Now to loop through it and print it with smarty:
{section name=i loop=$names}
Name:
{$names[i]}<br>
{/section}
A two dimensional associative array:
$smarty->assign('names', array(
array('name' => 'john', 'city' => 'Golden'),
array('name' => 'joe', 'city' => 'Bakersville'),
array('name' => 'eric', 'city' => 'Pleasantville'),
array('name' => 'matt', 'city' => 'TownCity'),
));
Displaying
with smarty:
{section
name=i loop=$names}
Name:
{$names[i].name}<br>
City: {$names[i].city}<br>
{/section}
To start a loop at a different value (default is
zero) use start:
{section
name=i loop=$names start=1} // will start looping at the value 1 rather
than zero
To
step through an array at a different value:
{section
name=i loop=$names step=2} // i will increment by 2's
Cycling
values:
{section
name=i loop=$names}
<tr
bgcolor="{cycle values="#aaaaaa,#bbbbbb"}">
<td>{$users[i].name}</td>
</tr>
{/section}
This will cycle the
background color for each row in the table
Predefined Variables
{* display value of page from URL (GET) http://www.domain.com/index.php?page=blah
*}
{$smarty.get.page}
{* display
the variable "page" from a form (POST) *}
{$smarty.post.page}
{* display
the value of the cookie "username" *}
{$smarty.cookies.username}
{* display
the server variable "SERVER_NAME" *}
{$smarty.server.SERVER_NAME}
A few more useful:
{$smarty.server.PHP_SELF} // will give the name of the current php app
(useful in forms)
{$smarty.section.i.iteration} //will return the current loop iteration
of the section named i
{$smarty.now|date_format:"%Y-%m-%d %H:%M:%S"} //will return
the current date formatted
There is quite
a bit more available in the smarty manual, it can do a lot!
|