Smarty also has what are known as template functions. Template functions carry out tasks in the template that may or may not display content. For example, you can include other templates from within a template with the include function. Let's say you have many templates with the same header and footer information. You can manage these as separate templates and include them.
| header.tpl | footer.tpl | |
|---|---|---|
<html>
<head>
<title>{$title|default:"no title"}</title>
</head>
<body>
|
</body> </html> |
|
| index.tpl | output | |
{include file="header.tpl" title="User Info"}
User Information:<p>
Name: {$name|capitalize}<br>
Address: {$address|escape}<br>
{include file="footer.tpl"}
|
|
One feature of the include function is locally scoped variables. Notice that $title is a template variable not assigned directly to the template, but assigned by passing it as an attribute to the include function. This way the $title variable is only available within the scope of the header template, and can be dynamically changed any time the header.tpl file is included. Also, notice we used the default modifier on $title so in the case $title is empty, the text "no title" will show up instead of displaying nothing.
There are some nice functions that automate tasks such as html dropdown boxes. One is html_options. You assign the arrays of data to the template, then this function does all the work to generate the HTML output for it.
| index.php |
|---|
include('Smarty.class.php');
// create object
$smarty = new Smarty;
// assign options arrays
$smarty->assign('id', array(1,2,3,4,5));
$smarty->assign('names', array('bob','jim','joe','jerry','fred'));
// display it
$smarty->display('index.tpl');
|
| index.tpl |
|---|
<select name=user>
{html_options values=$id output=$names selected="5"}
</select>
|
| output |
<select name=user> <option label="bob" value="1">bob</option> <option label="jim" value="2">jim</option> <option label="joe" value="3">joe</option> <option label="jerry" value="4">jerry</option> <option label="fred" value="5" selected="selected">fred</option> </select> |
Smarty facilitates a convenient way to loop over arrays of data with the section function. Here's an example of that, and we also threw in alternating row colors via the cycle function, and we use the strip function to strip out newlines and white space.


