Functions

This is the part of the guide where key functions essential to Smarty's power are finally revealed! Let's learn how to migrate away from embedding HTML inside our PHP files as so many of us have been guilty of before!

Note that these examples assume you are comfortable with PHP. Covering PHP programming is beyond the scope of this tutorial and should you need help there is plenty of documentation available at php.net.

Top

{include}

If you are familiar with PHP you are aware of the include function. Well, Smarty has one too that is equally essential! You would use the include function in Smarty for including other template files, such as a navigation menu for example. Let's take a look at some example template code. See Example 11 and Example 12 below.

The navigation.tpl file
<div id="nav">
  <a href="members.php" title="Members">Members</a>
  <a href="articles.php" title="Articles">Articles</a>
  <a href="news.php" title="News">News</a>
  <a href="index.php" title="Home">Home</a>
</div>

Let's look at the index.tpl file below.

The index.tpl file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Home</title>
</head>
<body>

{include file='navigation.tpl'}

<div>
  <p>Welcome!</p>
</div>

</body>
</html>
Top

{if}, {elseif}, {else}

Let's say that on our site's main page we have a welcome portion. Maybe we want to prompt the user to login if they are not already. And if the user is logged in, let's greet them personally with their name. We'll first take a look at what our PHP file might look like. See Example 13 below.

An example index.php file
<?php
// Grab our initialization file with our Smarty object defined
require_once('lib/init.php');

// Assuming we have code inside our functions.php file, let's see if the user is logged in
$is_logged_in = ($user->isLoggedIn()) ? true : false;

// Now if they are logged in let's grab their name and assign it
if ($logged_in) {
  $smarty->assign('name', $user->getUserName());
}

// Display our template
$smarty->display('index.tpl');
?>

Now let's create our index.tpl file. See Example 14 below.

An example index.tpl file
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>{$app_name} - Home</title>
</head>
<body>

{if ($is_logged_in)}
  <h1>Welcome {$name}!</h1>
{else}
  <h1>Welcome! Please <a href="login.php">login</a></h1>
{/if}

</body>
</html>

You can see that our template file is identical to HTML except for the Smarty variables are enclosed in curly brackets ({}) characters. Let's revisit this example using a more object oriented (OO) approach. See Example 15 below.

Note: From this point on all obvious HTML code will be removed (ex: DOCTYPE, head, body, etc.). The focus will be solely on the Smarty code!

An OO example of the index.php file
<?php
// Grab our initialization file with our Smarty object defined
require_once('lib/init.php');

// Let's hand the user object over to Smarty and let it handle the logic
$smarty->assign('user', $user);

// Display our template
$smarty->display('index.tpl');
?>

Now let's see how Smarty handles objects. Feel free to make use of the URL debugging option we enabled earlier to visualize what's happening! See Example 16 below.

An OO example of the index.tpl file
{if ($user->isLoggedIn())}
  <h1>Welcome {$user->getUserName()}!</h1>
{else}
  <h1>Welcome! Please <a href="login.php">login</a></h1>
{/if}

Smarty handles objects with the same syntax that PHP does! Let's see what Smarty can do with something a little more complex such as an array of objects.

Top

{foreach}, {foreachelse}

Let's say that we have an array of objects. A sample scenario would be a list of users and their information. Maybe we wish to iterate over the array of user objects and display a nice list with some of their information such as their name and ID.

As usual, we'll start with the PHP code first and then move on to the Smarty template code. Go ahead and set things up by creating a PHP file on your site named 'users.php'. Let's check out the code -- see Example 17 below.

An OO example of the users.php file
<?php
// Grab our intitialization file
require_once('lib/init.php');

// Let's assume we have a function that connects to our db
$link = getConnection();
$query = "SELECT f_name, l_name, user_id FROM users ORDER BY l_name ASC";

$result = mysql_query($query, $link);

$counter = 0;
while ($row = mysql_fetch_assoc($result) {
  // Assume our User class has a constructor that accepts
  // these parameters and assigns the object's properties
  $users[$counter] = new User($row);
  $counter++;
}

// Assign the array of objects to a smarty var
$smarty->assign('users', $users);
?>

Now we have an array of objects (hopefully!) and we are going to build our template file to work with it. Go ahead and create a file named 'users.tpl' inside your templates folder. See Example 18 below for the code!

An OO example of the users.tpl file
<h1>List of Users</h1>

{foreach from=$users item=user name=user_loop}
  {if $smarty.foreach.user_loop.first}<ul>{/if}
  <li>{$user->getLastName()}, {$user->getFirstName()} - <strong>{$user->getUserId()}</strong></li>
  {if $smarty.foreach.user_loop.last}</ul>{/if}
{foreachelse}
  <p>I'm sorry, no users were found.</p>
{/foreach}

Let's break down what is happening in our template file, users.tpl, shown above.

Some things to note about foreach loops:

Now let's take a look at an example of a key-value array

Example of a key-value array (PHP file)
<?php
$my_array = array( 0 => 'Tom',
                   1 => 'Ralph',
                   2 => 'Amy',
                   3 => 'Herman');
                 
$smarty->assign('my_array', $my_array);
?>

Now lets take a look at the template code below.

An example of a foreach loop with a key-value array (TPL file)
<h1>List of Users</h1>
{foreach from=$my_array key=my_key value=my_value name=user_loop}
  {if $smarty.foreach.user_loop.first}<ul>{/if}
  <li>$my_key: $my_value</li>
  {if $smarty.foreach.user_loop.last}</ul>{/if}
{foreachelse}
  <p>I'm sorry, no users were found.</p>
{/foreach}

<- Previous