Introduction

As aforementioned, Smarty is great at seperating code from design. Let's take a look at an example. Here is some poorly seperated PHP and HTML code.

<?php
$html = '<table>';
$html .= '<th>ID</th><th>Name</th><th>Address</th><th>Code</th>';
foreach $users as $element {
  $html .= '<td>' . $element['id'] . '</td>';
  $html .= '<td>' . $element['name'] . '</td>';
  $html .= '<td>' . $element['address'] . '</td>';
  $html .= '<td>' . $element['code'] . '</td>';
}
$html .= '</table>';
?>

Smarty can make this poorly constructed code much cleaner. But first you must know that Smarty works by having two seperate files in order to display a page. These files are a PHP file and a template file. Let's first look at the PHP file that would make the above example cleaner.

<?php
$smarty->assign('user_info', $users);
$smarty->display('users.tpl');
?>

Now let's take a look at the template file (users.tpl).

{html_table loop=$user_info cols="ID,Name,Address,Code"}

Not a Smarty fan yet? Keep on reading.

Next ->