PHP115
From mi-linux
Jump to navigationJump to searchMain Page >> Web Application Development >> Workbook >> Smarty Template Engine
Please note that this is an advanced topic. Make sure that you have worked through all the previous sections of this workbook before proceeding.
Installing Smarty
The tutorial on Smarty's official website are rather good, so let's go through them first:
Database example
I have created a simple database + Smarty example on mi-linux, here:
And here is the code for it:
The PHP files
The main file:
<?php // Set-up Smarty folders and connect to db require("setup_smarty.php"); require("connect_db.php"); // Get data $sql = "SELECT FilmNumber, FilmName, FilmGenre, FilmDuration FROM Films"; $myresult = mysql_query($sql); $total = mysql_num_rows($myresult); // Put data in array while ($row = mysql_fetch_assoc($myresult)) $results[] = $row; // Assign data to template $smarty->assign('total', $total); $smarty->assign('results', $results); // Display template $smarty->display('db.tpl'); ?>
As you can see it includes a couple of files:
- setup_smarty.php: Smarty set-up
- connect_db.php: connection to your database
<?php // setup_smarty.php // Include Smarty.class.php require('libs/Smarty.class.php'); // Create Smarty object $smarty = new Smarty(); // Set-up Smarty folders $smarty->template_dir = 'templates'; $smarty->compile_dir = 'templates_c'; $smarty->cache_dir = 'cache'; $smarty->config_dir = 'configs'; ?>
<?php //connect_db.php // Connect to db $dbServer=mysql_connect("localhost","xxxx","xxxx"); if (!$dbServer) {echo "Failed to connect to MySQL"; exit; } mysql_select_db("xxxx",$dbServer); ?>
Obviously you will need to amend the files above to suit your details (database credentials, paths to your folders etc.)
The templates
The main template:
{include file="header.tpl" title="Smarty rocks!"} <h1>Database example</h1> <p>Displaying {$total} records :</p> <table style="width:200px"> {section name=nr loop=$results} <tr style="background-color:{cycle values="#eeeeee,#dddddd"}"> <td>{$results[nr].FilmName}</td> <td>{$results[nr].FilmGenre}</td> </tr> {sectionelse} <tr><td>No results found!</td></tr> {/section} <table> {include file="footer.tpl"}
The header and footer (included above):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>{$title|default:"no title"}</title> </head> <body>
</body> </html>