Session 12: Server-Side, Part 2

Harvard University Extension School
Fall 2017

Course Web Site: http://cscie12.dce.harvard.edu/

Instructor email: david_heitmeyer@harvard.edu
Course staff email: cscie12@dce.harvard.edu

Topics

  1. Building Pages from Parts: An Introduction to PHP
  2. Web Development
  3. PHP Example with Courses from Database
  4. Using "View" templates - Model, View, * (MV*) Design Pattern
  5. {{Mustache}} Templates
  6. Hello! Greeting, Improved

slide1 slide2 slide3 slide4 slide5 slide6 slide7 slide8 slide9 slide10 slide11 slide12 slide13 slide14 slide15 slide16 slide17 slide18 slide19 slide20 slide21 slide22 slide23 slide24 slide25 slide26 slide27 slide28 slide29 

Building Pages from Parts: An Introduction to PHP

Review of HTTP Request/Response

simple http transaction

Pages from Parts

simple http transaction

Building a Page from Parts

PRISE

Why?

Techniques

Iroquois Constitution

Iroquois Constitution

Iroquois Constitution Zip File containing HTML, CSS, and "Include" files.

Iroquois ConstitutionIroquois Constitution

PHP: Hypertext Processor

From the PHP manual:

PHP, which stands for "PHP: Hypertext Preprocessor" is a widely-used Open Source general-purpose scripting language that is especially suited for Web development and can be embedded into HTML. Its syntax draws upon C, Java, and Perl, and is easy to learn. The main goal of the language is to allow web developers to write dynamically generated web pages quickly, but you can do much more with PHP.

cgi

PHP Example

hello.php

<?php
  $greeting = "Hello, World!";
?>
<html>
<head><title>Hello</title></head>
<body>
<h1><?php echo($greeting) ?></h1>
</body>                                                                                               
</html>

File Includes with PHP

Iroquois Constitution

<!DOCTYPE html>
<html>
  <head>
    <title>The Great Binding Law, Gayanashagowa (Constitution of the Iroquois Nations)</title>
   <?php include("inc/htmlhead.php"); ?>
  </head>
  <body id="part1">
   <?php include("inc/header.php"); ?>
   <?php include("inc/nav.php"); ?>
    <div id="main">
   <?php include("inc/content1.php"); ?>
    </div>
    <?php include("inc/footer.php"); ?>
  </body>
</html>

Files

|-- 1.php
|-- 10.php
|-- 11.php
|-- 12.php
|-- 13.php
|-- 14.php
|-- 15.php
|-- 16.php
|-- 2.php
|-- 3.php
|-- 4.php
|-- 5.php
|-- 6.php
|-- 7.php
|-- 8.php
|-- 9.php
|-- inc
|   |-- content1.php
|   |-- content10.php
|   |-- content11.php
|   |-- content12.php
|   |-- content13.php
|   |-- content14.php
|   |-- content15.php
|   |-- content16.php
|   |-- content2.php
|   |-- content3.php
|   |-- content4.php
|   |-- content5.php
|   |-- content6.php
|   |-- content7.php
|   |-- content8.php
|   |-- content9.php
|   |-- footer.php
|   |-- header.php
|   |-- htmlhead.php
|   |-- nav.php
|   `-- validate.php
|-- js
|   `-- highlightnavigation.js
`-- style.css

Parts that Build the Page

Iroquois Constitution

Starting File (1.php)

<!DOCTYPE html>
<html>
  <head>
    <title>The Great Binding Law, Gayanashagowa (Constitution of the Iroquois Nations)</title>
    <?php include("inc/htmlhead.php"); ?>
  </head>
  <body id="part1">
    <?php include("inc/header.php"); ?>
    <?php include("inc/nav.php"); ?>
    <div id="main">
      <?php include("inc/content1.php"); ?>
    </div>
    <?php include("inc/footer.php"); ?>
  </body>
</html>

HTML Head Content - htmlhead.php

<link rel="stylesheet" type="text/css" href="style.css" /> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript" src="js/highlightnavigation.js"> </script>

Header - header.php

<div id="header"><h1>Constitution of the Iroquois Nations</h1></div>

Navigation - nav.php

<div id="navigation">
<ul id="mainnav">
<li id="navpart1"><a href="1.php">The Great Binding Law, Gayanashagowa</a></li>
<li id="navpart2"><a href="2.php">Rights, Duties and Qualifications of Lords</a></li>
<li id="navpart3"><a href="3.php">Election of Pine Tree Chiefs</a></li>
<li id="navpart4"><a href="4.php">Names, Duties and Rights of War Chiefs</a></li>
<li id="navpart5"><a href="5.php">Clans and Consanguinity</a></li>
<li id="navpart6"><a href="6.php">Official Symbolism</a></li>
<li id="navpart7"><a href="7.php">Laws of Adoption</a></li>
<li id="navpart8"><a href="8.php">Laws of Emigration</a></li>
<li id="navpart9"><a href="9.php">Rights of Foreign Nations</a></li>
<li id="navpart10"><a href="10.php">Rights and Powers of War</a></li>
<li id="navpart11"><a href="11.php">Treason or Secession of a Nation</a></li>
<li id="navpart12"><a href="12.php">Rights of the People of the Five Nations</a></li>
<li id="navpart13"><a href="13.php">Religious Ceremonies Protected</a></li>
<li id="navpart14"><a href="14.php">The Installation Song</a></li>
<li id="navpart15"><a href="15.php">Protection of the House</a></li>
<li id="navpart16"><a href="16.php">Funeral Addresses</a></li>
</ul>
</div>

Footer - footer.php

<div id="footer">
Text form prepared by Gerald Murphy (The Cleveland Free-Net - aa300). Distributed by the Cybercasting Services Division of the National Public Telecomputing Network. Rendered into HTML by <a href="mailto:jon.roland@the-spa.com">Jon Roland</a> of the Constitution Society.  (NPTN). Permission is hereby granted to download, reprint, and/or otherwise redistribute this file, provided appropriate point of origin credit is given to the preparer(s), the National Public Telecomputing Network and the Constitution Society.
<div class="note">
<p>Additional information about the Iroquois nations and their constitution are available:</p>
<ul>
<li><a href="http://www.sixnations.org/">Haudenosaunee:  People Building a Long House</a></li>
<li><a href="http://www.tuscaroras.com/graydeer/influenc/page1.htm">The Influence of the Great Law of Peace on the the United States constitution:  an Haudenosaunee (Iroquois) Perspective</a></li>
<li><a href="http://www.ratical.org/many_worlds/6Nations/index.html">The Six Nations:  Oldest Living Participatory Democracy on Earth</a></li>
<li><a href="http://www.carnegiemuseums.org/cmnh/exhibits/north-south-east-west/iroquois/">The Iroquois nations of the Northeast</a></li>
<li><a href="http://www.iroquoismuseum.org/">Iroquois Indian Museum</a></li>
</ul>
</div>
<p>
  <?php include("validate.php"); ?>
</p>
</div>

Recommendation: Keep files well-formed

Don't do this: Breaking a page in half

This technique is not recommended. The first include file contains the top "half" of the page; the content follows; the second include file contains the bottom "half" of the page. In this technique, the html ,body, and perhaps other elements are started in the "top half" and their end tags are in "bottom half." The page delivered to the browser does validate, but the individual parts on the server are not well-formed, which can cause some confusion when editing a file.

<?php include("header-tophalf.html"); ?>
  Lorem ipsum dolor sit amet, consectetuer adipiscing ...
<?php include("footer-bottomhalf.html"); ?>

ssi

Keeping things well-formed

<!DOCTYPE html>
<html>
  <head>
    <title>Lecture Notes</title>
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>
    <div id="header">
      <?php include("inc/header.php") ?>
    </div>
    <div id="navigation">
      <?php include("inc/nav.php") ?>
    </div>
    <div id="main">
      Lorem ipsum dolor sit amet, consectetuer adipiscing ...
    </div>
  </body>
</html>

Web Development

LanguageFrameworks/Platforms
JavaScript Node, Angular, Backbone, Ember
PHPLaravel, Symfony, CodeIgniter, CakePHP
CMS: Drupal, Joomla, Concrete5, GetSimple
PythonDjango, CherryPy, Flask, Zope, Plone
RubyRails
PerlCatalyst, Dancer, Mojolicious
JavaStruts, Sling, JSF, Wicket, Tapestry, Grails
C#ASP.NET, ASP.NET MVC Framework, others

Dynamic Content

Dynamic Content: How does it look?

Web Program Examples

Markup or content is embedded within a program; program embedded into markup

first.pl - Perl

first.pl

#!/usr/local/bin/perl
print "Content-type: text/html\n\n";
print "<html><body><h1>Hello, World!</h1></body></html>";

first.py - Python

first.py

#!/usr/bin/python
print "Content-type: text/html\n\n";
print "<html><head><title>Hello World!</title></head>";
print "<body><h1>Hello, World!</h1></body></html>";

first.php - PHP

first.php

<?php
echo('<html><head><title>First PHP</title></head><body>');
echo('<h1>Hello!</h1>');
echo('</body></html>');
?>

second.php - PHP

second.php
program statements within markup

<?php
      $title = "Hello World!";
?>
<!DOCTYPE html>
  <head>
    <meta charset="utf-8" />
    <title><?php echo($title) ?></title>
  </head>
  <body>
    <h1><?php echo($title) ?></h1>
  </body>
</html>

A Personal Greeting

<?php
      $name = $_GET["name"];
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Greeting Page</title>
  </head>
  <body>
    <h1>Hello, <?php echo($name) ?>!</h1>
  </body>
</html>

A Personal Greeting

Without a "name", present the user a form. With a name, provide a greeting.

<?php
      $name = $_GET["name"];
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8"/>
    <title>Greeting Page</title>
  </head>
  <body>
    <?php
    if ($name) {
      echo("<h1>Hello, $name!</h1>");
    } else {
      echo('<h1><label for="input_name">Enter name:</label></h1>');
      echo('<form method="get">');
      echo('<input type="text" name="name" id="input_name"/>');
      echo('<br /><input type="submit" />');
      echo('<br /><input type="reset" />');
    }
?>
  </body>
</html>
    

PHP Example with Courses from Database

courses

courses

FAS Course Data

Data Table

Course data for Faculty of Arts & Sciences is in a mysql database on cscie12students (username: class; database name: coursecatalog)

SQL:

describe courses

Terminal:

cscie12students$ mysql -u class coursecatalog
Welcome to the MySQL monitor.  Commands end with ; or \g.

mysql> describe courses;
+------------------------------+--------------+------+-----+---------+-------+
| Field                        | Type         | Null | Key | Default | Extra |
+------------------------------+--------------+------+-----+---------+-------+
| acad_year                    | year(4)      | YES  |     | NULL    |       |
| cat_num                      | int(9)       | YES  |     | NULL    |       |
| offered                      | char(1)      | YES  |     | NULL    |       |
| department_code              | varchar(15)  | YES  |     | NULL    |       |
| department_short             | varchar(80)  | YES  |     | NULL    |       |
| department_long              | varchar(200) | YES  |     | NULL    |       |
| course_group_code            | varchar(10)  | YES  |     | NULL    |       |
| course_group_long            | varchar(200) | YES  |     | NULL    |       |
| num_int                      | int(9)       | YES  |     | NULL    |       |
| num_char                     | varchar(15)  | YES  |     | NULL    |       |
| term_pattern_code            | int(5)       | YES  |     | NULL    |       |
| fall_term                    | char(1)      | YES  |     | NULL    |       |
| spring_term                  | char(1)      | YES  |     | NULL    |       |
| term                         | varchar(100) | YES  |     | NULL    |       |
| title                        | text         | YES  |     | NULL    |       |
| course_type                  | varchar(100) | YES  |     | NULL    |       |
| course_level_code            | char(1)      | YES  |     | NULL    |       |
| course_level                 | varchar(200) | YES  |     | NULL    |       |
| credit_code                  | int(5)       | YES  |     | NULL    |       |
| credit                       | varchar(50)  | YES  |     | NULL    |       |
| instructor_approval_required | char(1)      | YES  |     | NULL    |       |
| meeting_time                 | text         | YES  |     | NULL    |       |
| faculty_text                 | text         | YES  |     | NULL    |       |
| description                  | text         | YES  |     | NULL    |       |
| prerequisites                | text         | YES  |     | NULL    |       |
| notes                        | text         | YES  |     | NULL    |       |
+------------------------------+--------------+------+-----+---------+-------+
26 rows in set (0.00 sec)

SQL

SQL:

select distinct department_short from courses

Terminal:

mysql> select distinct department_short from courses;
+----------------------------------------------------------+
| department_short                                         |
+----------------------------------------------------------+
| African and African American Studies                     |
| American Studies                                         |
| Anthropology                                             |
| Architecture, Landscape Architecture, and Urban Planning |
| Asian Studies Programs                                   |
| Astronomy                                                |
| Biological Sciences in Dental Medicine                   |
| Biological Sciences in Public Health                     |
| Biophysics                                               |
| Biostatistics                                            |
| Celtic Languages and Literatures                         |
| Chemical Biology                                         |
| Chemical and Physical Biology                            |
| Chemistry and Chemical Biology                           |
| Comparative Literature                                   |
| Dramatic Arts                                            |
| Earth and Planetary Sciences                             |
| East Asian Languages and Civilizations                   |
| Economics                                                |
| Engineering and Applied Sciences                         |
| English                                                  |
| Environmental Science and Public Policy                  |
| Expository Writing                                       |
| Folklore and Mythology                                   |
| Freshman Seminars                                        |
| General Education                                        |
| Germanic Languages and Literatures                       |
| Global Health and Health Policy                          |
| Government                                               |
| Health Policy                                            |
| History                                                  |
| History and Literature                                   |
| History of Art and Architecture                          |
| History of Science                                       |
| House Seminars                                           |
| Human Evolutionary Biology                               |
| Humanities                                               |
| Life Sciences                                            |
| Linguistics                                              |
| Mathematics                                              |
| Medical Sciences                                         |
| Medieval Studies                                         |
| Middle Eastern Studies                                   |
| Mind, Brain, and Behavior                                |
| Molecular and Cellular Biology                           |
| Music                                                    |
| Near Eastern Languages and Civilizations                 |
| Neurobiology                                             |
| No Department                                            |
| Organismic and Evolutionary Biology                      |
| Philosophy                                               |
| Physical Sciences                                        |
| Physics                                                  |
| Psychology                                               |
| Regional Studies - East Asia                             |
| Romance Languages and Literatures                        |
| Russia, Eastern Europe, and Central Asia                 |
| Slavic Languages and Literatures                         |
| Social Policy                                            |
| Social Studies                                           |
| Sociology                                                |
| South Asian Studies                                      |
| Special Concentrations                                   |
| Statistics                                               |
| Stem Cell and Regenerative Biology                       |
| Studies of Women, Gender, and Sexuality                  |
| Systems Biology                                          |
| The Classics                                             |
| The Study of Religion                                    |
| Ukrainian Studies                                        |
| Visual and Environmental Studies                         |
+----------------------------------------------------------+
71 rows in set (0.01 sec)

PHP Script to Connect to Database and Get List of Departments

#!/usr/bin/php
<?php
// 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';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// iterating through results
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  echo $row['department_code'];
  echo "\t";
  echo $row['department_short'];
  echo "\n";
}
?>

Output

Turn this into HTML Output

<?php
// 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';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Printing results in HTML
echo "<ul>\n";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "<li>";
    echo $row['department_short'];
    echo "</li>\n";
 }
echo "</ul>\n";
?>

The entire "departments-simple.php"

<!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>

<?php
// 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';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// iterating through results
echo "<ul>\n";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    echo "<li>";
    echo $row['department_short'];
    echo "</li>\n";
 }
echo "</ul>\n";


// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?>

 </body>
</html>

Adding another view - Department Course Listings

Create another PHP file that displays course information based upon a department_code parameter.

Need to link to to courses.php:

Modify the department listing to include the hyperlink:

<!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>
<?php
// 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';
$result = mysql_query($query) or die('Query failed: ' . mysql_error());

// Printing results in HTML
echo "<ul>\n";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
  echo "<li>";
  echo "<a href=\"courses.php?department_code=$row[department_code]\">$row[department_short]</a>";
  echo "</li>\n";
}
echo "</ul>\n";

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?> 

</body>
</html>

courses.php

<!DOCTYPE html>
<html>
 <head>
  <title>FAS Courses</title>
  <link rel="stylesheet" href="site.css" type="text/css"/>
 </head>
 <body>
<h1>Faculty of Arts &amp; Sciences</h1>
<p><a href="departments.php">Return to Department List</a></p>
<h2>Department <?php echo $_GET[department_code] ?></h2>
<?php
// 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');

$dept_code = $_GET['department_code'];

// Performing SQL query
$query = 'SELECT course_group_long, num_int, num_char, term, title, description, faculty_text';
$query .= ' from courses where department_code = ';
$query .= "'".mysql_escape_string($dept_code)."'";
$query .= ' order by course_group_long, num_int, num_char, title';

$result = mysql_query($query) or die('Query failed: ' . mysql_error());
// Printing results in HTML
     echo "<table cellspacing='0' cellpadding='0'>\n";
$i = 0;
     while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
       $class = $i++ % 2 ? 'evenrow' : 'oddrow' ;
       echo "\t<tr class='$class'>\n";
       echo "<td class='abbrev'>$row[course_group_long] $row[num_int] $row[num_char]</td>";
       echo "<td class='long'><strong>$row[title]</strong><br/>$row[faculty_text]";
       echo "<p class='description'>$row[description]</p></td>";
       echo "\t</tr>\n";
     }
echo "</table>\n";

// Free resultset
mysql_free_result($result);

// Closing connection
mysql_close($link);
?> 

</body>
</html>

Using "View" templates - Model, View, * (MV*) Design Pattern

Variations: Controller, Presenter, ViewModel, Whatever

MVC

MVC design pattern separates:


You can adopt this design pattern regardless of language or server-architecture. Some frameworks make using MV* possible, some make it easy, some insist on it.

PHP Smarty Templates

smarty

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);
?> 

Smarty Template for Courses

smarty

The template (courses.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>
<p><a href="smarty-dept.php">Return to Department List</a></p>
<h2>Department {$department_code}</h2>
<table cellspacing="0" cellpadding="0">
{foreach from=$courses item=course name=courses}
<tr class="{cycle values="row1,row2,row3,row4"}">
<td class="abbrev">{$course.course_group_long} {$course.num_int}{$course.num_char}</td>
<td class="long">
  <strong>{$course.title}</strong><br/>
  <span class="faculty">{$course.faculty_text}</span>
  <p class="description">
    {$course.description}
  </p>
</td>
</tr>
{/foreach}
</table>
</body>
</html>

Get the Courses for the CHEM department: smarty-courses.php?department_code=CHEM

The SQL:

SELECT course_group_long, 
              num_int, num_char, term,
              title, description 

smarty-course.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 course_group_long, num_int, num_char, term, title, description, faculty_text';
$query .= ' from courses where department_code = ';
$query .= "'".mysql_escape_string($_GET['department_code'])."'";
$query .= ' order by course_group_long, num_int, num_char, title';
$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;
// pass the results to the template
$smarty->assign('courses', $results); 
$smarty->assign('department_code', $_GET['department_code']);
    
$smarty->template_dir = './smarty_templates';
$smarty->compile_dir = '/tmp/smarty/templates_c';
$smarty->cache_dir = '/tmp/smarty/cache';
$smarty->config_dir = './smarty_configs';

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

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

{{Mustache}} Templates

{{mustache}} is another widely used template system for JavaScript (and other languages!).

mustache

Mustache Departments

Mustache Template

mustache-dept.php

PHP

<?php
// 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;
}

$template_data['departments'] = $results;

// Process with Mustache Template
include('lib/Mustache.php');

$m = new Mustache;
$template_file = 'mustache_templates/departments.html';
$template_contents = file_get_contents($template_file);
echo $m->render($template_contents, $template_data);

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

Mustache Template

mustache_templates/departments.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <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>
{{#departments}}
     <li>
       <a href="mustache-courses.php?department_code={{department_code}}">{{department_short}}</a>
     </li>
{{/departments}}
</ul>
  </body>
</html> 

Mustache Courses

<!DOCTYPE html>
<html>
 <head>
  <title>Courses: {{department_name}}</title>
  <link rel="stylesheet" href="site.css" type="text/css"/>
 </head>
 <body>
<h1>Faculty of Arts &amp; Sciences</h1>
<p><a href="mustache-dept.php">Return to Department List</a></p>
<h2>{{department_name}}</h2>
<table cellspacing="0" cellpadding="0">
{{#courses}}
<tr>
<td class="abbrev">{{course_group_long}} {{num_int}}{{num_char}}</td>
<td class="long">
  <strong>{{title}}</strong>
  <br/>
  <span class="faculty">{{faculty_text}}</span>
  <p class="description">
    {{description}}
  </p>
</td>
</tr>
{{/courses}}
</table>
</body>
</html>

Hello! Greeting, Improved

Without a "name", present the user a form. With a name, provide a greeting.

<?php
      $name = $_GET["name"];
?>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Greeting Page</title>
  </head>
  <body>
    <?php
      if ($name) {
        echo("<h1>Hello, $name!</h1>");
      } else {
        echo('<h1><label for="input_name">Enter name:</label></h1>');
        echo('<form method="get">');
        echo('<input type="text" name="name" id="input_name"/>');
        echo('<br /><input type="submit" />');
        echo('<br /><input type="reset" />');
      }
    ?>
  </body>
</html>

Greeting, Improved

Three files: one code; two templates

index.php

<?php 
$name = $_GET["name"];

// figure out which template is needed
if ($name) {
  $template_file = 'greeting.html';
} else {
  $template_file = 'form.html';
}
$template_contents = file_get_contents($template_file);
$template_data['name'] = $name;

// Process with Mustache Template
include('lib/Mustache.php');
$m = new Mustache;

echo $m->render($template_contents, $template_data);

?>

greeting.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Greeting Page for {{name}}</title>
  </head>
  <body>
      <h1>Hello, {{name}}!</h1>
  </body>
</html>

form.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>Greeting Page</title>
  </head>
  <body>
      <h1><label for="input_name">Enter name:</label></h1>
      <form method="get">
      <input type="text" name="name" id="input_name"/>
      <br /><input type="submit" />
      <br /><input type="reset" />
  </body>
</html> 

Copyright © David Heitmeyer