Harvard Extension School
CSCI E-12 Fundamentals of Web Site Development | Spring 2019

## 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 &amp; 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
    $link = mysql_connect('localhost', 'class', 'dbpasswd')
         or die('Could not connect: ' . mysql_error());

    mysql_select_db('coursecatalog') or die('Could not select database');
    // Performing SQL query
    $query = 'SELECT distinct department_short, department_code FROM courses order by department_short';
    $res = mysql_query($query) or die('Query failed: ' . mysql_error());
    $i=0;
    while ($row = mysql_fetch_array($res, MYSQL_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';

    $smarty->assign('dept', $results);

    // display it
    $smarty->display('departments.tpl');

    /* ==================================================
        Cleanup
       ================================================== */
    // Free resultset
    mysql_free_result($res);
    // Closing connection
    mysql_close($link);
    ?>

Copyright © David Heitmeyer