Semantic Errors

Let’s start our first foray into template debugging by creating a simple PHP script and an accompanying Smarty template. It will serve as a contact form for a fictitious company, but it will be a good start for our examples. Here are the files:

Create a file called index.php and put the following content in it:

<?php
include_once(‘libs/Smarty.class.php’);
$smarty = new Smarty;

$departments = array(
    ‘marketing’ => ‘Marketing Department’,
    ‘sales’     => ‘Sales Department’,
    ‘support’   => ‘Customer Service Department’
);
$smarty->assign(‘departments’, $departments);

$smarty->display(‘index.tpl’);
?>

Create a new file called index.tpl with the following:

<html>
<head>
<title>Example Corp.</title>
</head>
<body>
<h3>Example Corp. - Contact Us</h3>

<p>
  Please choose the department that you are trying to contact, and your
  contact details, and we will get back to you within 48 hours.
</p>

<form method=”post” action=”contact_handler.php”>
<table border=”1”>
  <tr>
    <td><b>Department:</b></td>
    <td>
      {foreach key=”name” item=”description” from=$department}
      <input type=”radio” name=”dept” value=”{$name}”> {$description}<br />
      {/foreach}
    </td>
  </tr>
  <tr>
    <td><b>Your Details:</b></td>
    <td>
      <input type=”text” name=”details” size=”40”>
    </td>
  </tr>
  <tr>
    <td colspan=”2”>
      <b>Message:</b><br />
      <textarea name=”message” style=”width: 100%;”></textarea>
    </td>
  </tr>
  <tr>
    <td colspan=”2”><input type=”submit” value=”Send Message”></td>
  </tr>
</table>
</form>

</body>
</html>

After opening the PHP script on your web browser, your output should look like:

Semantic Errors

As you can see from the screenshot on the facing page, something is clearly wrong. The template code we created should iterate over the list of available departments, and print each as a different radio box. However, nothing is being displayed. In this case, we first check if the PHP script is passing the correct values to the template. We find that it is indeed passing an associative array of department names and their descriptions.

Next, we check if the Smarty template is using the proper variable name. Aha, there is indeed a problem here. The PHP script calls the list of department names $departments, but the Smarty template is using the unknown variable name $department instead. By changing the template file to reference the correct variable name, the actual department names will be displayed as shown:

Semantic Errors
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.86.138