PHP Smarty Templates
- Smarty
is a Template Engine for PHP, which allows you to write Templates for your PHP data.
The template (departments.tpl):
<!DOCTYPE html>
<html>
<head>
<title>Departments</title>
<link rel="stylesheet" href="site.css" type="text/css"/>
</head>
<body>
<h1>Faculty of Arts & Sciences</h1>
<h2>Departments</h2>
<ul>
{foreach from=$dept item=d}
<li>
<a href="smarty-courses.php?department_code={$d.department_code}">{$d.department_short}</a>
</li>
{/foreach}
</ul>
</body>
</html>
Get the departments: smarty-dept.php
<?php
/* ==================================================
Database Stuff
================================================== */
/// Connecting, selecting database
$mysqli = new mysqli('localhost','class','cscie12','coursecatalog');
if ($mysqli->connect_errno) {
echo "Failed to connect to mysql: ".$mysqli->connect_errno." ".$mysqli->connect_error;
}
// Performing SQL query
$query = 'SELECT distinct department_short, department_code FROM courses order by department_short';
$result = $mysqli->query($query);
$i=0;
while ($row = $result->fetch_assoc()) {
$results[$i++] = $row;
}
/* ==================================================
Smarty Template Stuff
================================================== */
require('/usr/local/lib/php/Smarty/Smarty.class.php');
// create object
$smarty = new Smarty;
$smarty->template_dir = './smarty_templates';
$smarty->compile_dir = '/tmp/smarty/templates_c';
$smarty->cache_dir = '/tmp/smarty/cache';
$smarty->config_dir = './smarty_configs';
// assign some content. This would typically come from
// a database or other source, but we'll use static
// values for the purpose of this example.
$smarty->assign('dept', $results);
// display it
$smarty->display('departments.tpl');
/* ==================================================
Cleanup
================================================== */
// free and close
$result->free();
$mysqli->close();
?>