Templates in the Real World

Now that we have discussed the basics, let’s see how templates work in real-world problems. We will show you how to develop some templates that can solve your everyday problems. These are listed below:

  • Calendar
  • Generalized Database Reports
  • Data Input Forms
  • Email Newsletter

Calendar

Calendar is a HTML gadget you may occasionally need for a website. If you plan to develop a calendar, don’t worry about writing many lines of code. Using Smarty, you can develop it in a very straightforward way. Let’s see how.

calendar.tpl

<b>{$title}</b>
{html_table loop=$special_days cols=7}
</body>
</html>

In this template, we use a special Smarty function named {html_table}. We will discuss this in detail, later in this section. First let’s take a look at the PHP script that assigns the variables to display the calendar.

calendar.php

<?
    include(“libs/smarty.class.php”);
    $smarty = new smarty();
    
    $date = “10/01/2005”; //October 01, 2005
    $week_days = array(“Sat”=>1, “Sun”=>2, “Mon”=>3,”Tue”=>4,”Wed”=>5, “Thu”=>6,”Fri”=>7);
    
    $total_day_of_month = get_total_day($date);
    $starting_day = $week_days[Date(“D”,strtotime($date))] - 1;
    foreach (array_keys($week_days) as $day)
    $days[] = $day;
    for ($i=0; $i<$starting_day; $i++)
    $days[] = “&nbsp;”;
    for ($i=1; $i< ($total_day_of_month+1); $i++)
    $days[] = $i;
    
    $smarty->assign(“title”,”October 2005”);
    $smarty->assign(“special_days”, $days);
    $smarty->display(“calendar.tpl”);
    
function get_total_day($date)
{
    $time_stamp = strtotime($date);
    $month_ar = split(“/”, $date);
    $month = $month_ar[0];
    $year = Date(“Y”,$time_stamp);
    for ($i=28; $i<33; $i++)
    {
        if (!checkdate($month, $i, $year)){
            return ($i - 1);
        }
    }
}
    
?>

If you run this script in a browser you will see the following output:

Calendar

Note that in the code, we supplied the date in the $date variable. If you change it to 11/01/05 then you will see the following output.

Calendar

That’s it, you’re done!. Have you noticed how small the template is? As we said, we use a special Smarty function {html_table}. This takes an array as parameter and an optional column number. By default the column number is set to 3. Here we need seven columns for a calendar, so we specified cols=7. Then it displays the array as a table splitting it into specified number of columns in each row.

Database Report

Database reports are the most common examples where Smarty is used. With Smarty, you can develop smashing reports in a minute. However, if you want to your reports to look good, you must have some knowledge about CSS. For this example, we have the following tables:

mysql> DESC agents;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| area       | varchar(50)  |      |     |         |       |
| agent_id   | int(11)      |      |     | 0       |       |
| agent_name | varchar(255) |      |     |         |       |
+------------+--------------+------+-----+---------+-------+

mysql> DESC items;
+------------+--------------+------+-----+---------+-------+
| Field      | Type         | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+-------+
| item_id    | varchar(10)  |      |     |         |       |
| item_name  | varchar(255) |      |     |         |       |
| item_price | int(11)      |      |     | 0       |       |
+------------+--------------+------+-----+---------+-------+

mysql> DESC sales;
+----------+-------------+------+-----+---------+-------+
| Field    | Type        | Null | Key | Default | Extra |
+----------+-------------+------+-----+---------+-------+
| agent_id | int(11)     |      |     | 0       |       |
| item_id  | varchar(10) |      |     | 0       |       |
| quantity | int(11)     |      |     | 0       |       |
+----------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)

database_report.php

<?
include(“libs/smarty.class.php”);
$smarty= new smarty();
mysql_connect(“localhost”,”root”,”root”);
mysql_select_db(“smarty”);
$result = mysql_query(“SELECT area,
                              agent_name, 
                              item_name, 
                              quantity, 
                              item_price, 
                              (quantity*item_price) as total 
                       FROM   agents 
          INNER JOIN sales on agents.agent_id = sales.agent_id
          INNER JOIN items on sales.item_id = items.item_id 
          ORDER BY area ASC”);
while ($row = mysql_fetch_assoc($result))
{
	$areas[] = $row[‘area’];
	$agents[] = $row[‘agent_name’];
	$items[] = $row[‘item_name’];
	$quantities[] = $row[‘quantity’];
	$total[] = $row[‘total’];
}

$fields = array(“area”, “agent”, “item”, “quantity”, “total”);

$smarty->assign(“areas”, $areas);
$smarty->assign(“agents”, $agents);
$smarty->assign(“items”, $items);
$smarty->assign(“quantities”, $quantities);
$smarty->assign(“total”, $total);
$smarty->assign(“fields”, $fields);
$smarty->display(“database_report.tpl”);
mysql_free_result($result);
?>

This script executes a query and fetches the records. It then makes an array of each item and assigns it to a Smarty variable. Now, it’s time to develop the template for the report. Let’s go.

database_report.tpl

<html>
<body>
<table cellpadding=”4” border=”1” cellspacing=”0”><tr>
{section name=id loop=$fields}
<th>{$fields[id]}</th>
{/section}
</tr>
{section name=data loop=$areas}
<tr>
<td>{$areas[data]}</td>
<td>{$agents[data]}</td>
<td>{$items[data]}</td>
<td>{$quantities[data]}</td>
<td>{$total[data]}</td>
</tr>
{/section}
</table>
</body>
</html>

Now run this script and you will get the following output:

Database Report

You get a basic database report with not much attention paid to its presentation and look. The template code is so simple that Smarty beginners can easily understand it. Let’s see how we can make this report look better with another Smarty function, cycle.

cycle is a Smarty function that just cycles through a set of values and returns them one by one. This function is extremely useful when you are trying to choose alternating values for a specific purpose. For an example, if we change the background color of every <tr> element then definitely it will look more pleasant. Let’s see the {cycle} function in action. Just replace the <tr> on the ninth line in the above template with the following code:

<tr bgcolor=’{cycle values=”#EBEBEB, #ACABAB”}’>

Now run the script and you will see the following output:

Database Report

Smarty gives you extremely powerful functions for doing everything you would like to.

Let’s apply some CSS over your template. We will just change the <th> style, and remove the table border and add the following style definition at the beginning of the database_report.tpl file.

<style>
#report_table th{
    border: 1px solid; 
    /*padding-left: 15px;*/
    padding-right: 30px;
    color: #EEEEEC;
    background-color: #25510D;
    text-align: left;
}
#report_table {
    border: 1px solid #cccccc;
}
</style>

We will also replace the third line of our previous template code with this one:

<table cellpadding=”4” border=”0” cellspacing=”1” id=’report_table’ ><tr>

Now see the output.

Database Report

Just note that we used a specific table id and CSS only to avoid CSS cross referencing. Always practice this to avoid unexpected results.

Data Input Forms

Data input forms are required in almost all web applications. Smarty provides some helpful functions to better your form design process. These functions output some HTML objects that generally take time to process via PHP or JavaScript. They come handy when you want to retrieve some information and display it in the edit mode.

For example, let’s assume your user has entered his or her skill matrix in different checkboxes. Now you have to retrieve this information from the database and show it in the same format as your user entered it initially: that is, some checkboxes remain checked while others remain unchecked. This scenario becomes extremely complex if you want to achieve this using only PHP.

In the following example, we will make a user survey form and show it in edit mode according to your user’s given input. We should have a combo box, checkbox and radio buttons in our input form. We will not go through the details of saving this data in a database. Instead we will concentrate on techniques for displaying it in edit mode.

survey.tpl

<html>
<head>
<title>Survey Form</title>
<style type=”text/css”>
{literal}
body,td,th {
	font-family: Verdana, Arial, Helvetica, sans-serif;
	font-size: 12px;
}
{/literal}
</style>
</head>
<body>
<p><strong>Survey Form</strong></p>
<form name=”survey_form” method=”post” action=””>
  <table width=”339” border=”0” cellpadding=”4” cellspacing=”0”>
    <tr>
      <td width=”165”>Name: </td>
      <td width=”158”><input name=”name” type=”text” id=”name”value=”{$name}”></td>
    </tr>
    <tr>
      <td>Email: </td>
      <td><input name=”email” type=”text” id=”email” value=”{$email}”></td>
    </tr>
    <tr>
      <td>Country: </td>
      <td><select name=”country”>
        {html_options options=$countries selected=$country}
      </select></td>
    </tr>
    <tr>
      <td>State: </td>
      <td><select name=”state”>
        {html_options options=$states selected=$state}
                  </select></td>
    </tr>
    <tr>
      <td valign=”top”>Company Name: </td>
      <td><p>
        <input type=”text” name=”company_name”>
        <br>
        {$company_start}</p>      </td>
    </tr>
    <tr>
      <td valign=”top”>Company Starts: </td>
      <td>{html_select_date}</td>
    </tr>
    <tr>
      <td valign=”top”>Yearly Revenue of your Company: </td>
      <td>{html_radios name=”yearly_revenue” options=$revenues selected=$revenue separator=”<br />”}
</td>
    </tr>
    <tr>
      <td valign=”top”>Primary OS: </td>
      <td>
      <p>{html_checkboxes name=”os” options=$oses selected=$os separator=”<br />”}</p>       
      </td>
    </tr>
  </table>
</form>
</body>
</html>

survey.php

<?
include_once(“libs/smarty.class.php”);
$smarty =new smarty();

$smarty->assign(“name”, “Junayed Ahnaf”);
$smarty->assign(“email”, “[email protected]”);

$countries = array(“Bangladesh”, “India”, “Pakistan”, “Nepal”, “Maldives”, “Srilanka”, “Bhutan”);
$country = 0;
$smarty->assign(“countries”, $countries);
$smarty->assign(“country”, $country);

$states = array(“state1”, “state2”, “state3”, “state4”, “state5”);
$state = 3;
$smarty->assign(“states”, $states);
$smarty->assign(“state”, $state);

$smarty->assign(“company_name”, “My World”);
$smarty->assign(“company_start_date”, “12/2001”);

$smarty->assign(‘revenues’, array(
            1 => ‘$0-$10000’,
            2 => ‘$10000-$20000’,
            3 => ‘$20000-$50000’,
            4 => ‘$50000+’));
$smarty->assign(‘revenue’, 2);

$smarty->assign(‘oses’, array(
           1 => ‘Windows XP’,
            2 => ‘Linux’,
            3 => ‘Sun Solaris’,
            4 => ‘Mac OS’));
$smarty->assign(“os”, array(2,1));
$smarty->display(“survey.tpl”);
?>	

To keep the coding simple, I hard-coded the variable assignments in the above example. In a real-life application, of course, this data would be retrieved from a database or other source.

The first time that the user visits this page, these variables have no value. The visitor will see all those HTML objects with no pre-selected value at all. When the user selects something then we will store it in the database.

The main goal of this example is to show how to retrieve the data items and show them in edit mode while keeping the code simple. Let’s see how the form will be displayed in a browser for first time.

Data Input Forms

In this template we used some special Smarty functions like {html_radios}, {html_checkboxes}, {html_select_date}, and {html_options}. {html_radios} and {html_checkboxes} are used to generate a group of radio buttons and checkboxes. Moreover, you can define the values that will be pre-selected for these functions. This feature makes them usable in real life, because pre-selecting these checkboxes with retrieved information is a big hassle, whether you do it on the server side or client side. Smarty makes it easy for template designers. {html_select_date} returns a set of combo boxes to make it easy to select dates. You can control the range of years and dates. {html_select_date} has a similar sibling that just gives you the facility to select time instead of date; this is {html_select_time}. We will discuss these functions in detail in Chapter 6.

Email Newsletter

Newsletters are a very popular way to broadcast news about the products of a company or whatever. Due to extensive use of email, these days email newsletters are gaining popularity. You can use Smarty to generate attractive newsletters for your users and send them as HTML mail. Here we will show you a fixed design for this, but in practice you would like to pre-design a bunch of templates for your newsletters. In this example, we will generate a newsletter with Smarty and broadcast it using the MIME mail sending capability of PHP.

newsletter.tpl

<table width=”90%”  border=”0” align=”center” cellspacing=”5”>
  <tr>
    <td bgcolor=”#FFFFFF”><img src=”http://www.packtpub.com/images/Packt.png”></td>
    <td><div align=”right”>
      <h3>Newsletter Issue {$issue} {$month}, {$year} </h3>
    </div></td>
  </tr>
  <tr>
    <td width=”31%” bgcolor=”#999999”><table width=”100%”  border=”0” cellpadding=”0” cellspacing=”1”>
      <tr>
        <td bgcolor=”#999999”><div align=”center”><strong>Books published in this week </strong></div></td>
      </tr>
      {section name=book loop=$books}
      <tr>
        <td bgcolor=”#FFFFFF”><div align=”center”><img src=’{$images[book]}’ vspace=”2”><br /> 
          <b>{$books[book]}</b> </div></td>
      </tr>
      {/section}
    </table></td>
    <td width=”69%” valign=”top”>
    <p>
        <b>{$reviews.title}</b><br/>
        {$reviews.description}<br/>
        Read More : <a href=’{$reviews.link}’>Click Here</a>
    </p>    </td>
  </tr>
  <tr>
    <td colspan=”2”><div align=”center”> &copy; Packt Publishing Ltd 2005 </div></td>
  </tr>
</table>

This is an imaginary newsletter for Packt Publishing. Let’s assume they plan to distribute it weekly with news of published titles and reviews about their books particular to that week. We will now look at the script to generate a newsletter from this template and send it as an HTML mail to users who subscribed to receive their newsletter. Following is a preview of our newsletter.

Email Newsletter

newsletter.php

<?
include (“libs/smarty.class.php”);
$smarty = new smarty();

$smarty->assign(“issue”, 3);
$smarty->assign(“month”,”October”);
$smarty->assign(“year”, 2005);

$books = array(“Building websites with Mambo”,”Building Telephony Systems With Asterisk”);
$images = array(“http://www.packtpub.com/images/73x90/1904811736.png”,”http://www.packtpub.com/images/73x90/1904811159.png”);

$smarty->assign(“books”, $books);
$smarty->assign(“images”, $images);

$review = <<< END
An easy introduction to using and configuring Asterisk to build feature-rich telephony systems for small and medium businesses.
This book shows how to build a telephony system for your home or business using the free and open source application, Asterisk. ‘Building a Telephony System with Asterisk’ takes you step-by-step through the process of installing and configuring Asterisk. It shows you how to make a deployment plan, and how to create a dial plan.
END;
$link = “http://www.packtpub.com/asterisk/book”;
$title = “Building Telephony Systems With Asterisk”;
$reviews = array(“title”=>$title, 
                 “description”=>$review,
                 “link”=>$link);
$smarty->assign(“reviews”, $reviews);

$output = $smarty->fetch(“newsletter.tpl”);                

$user = “[email protected]”;

$headers = “MIME-Version: 1.0 
” ;
$headers .= “Content-Type: text/html; charset=iso-8859-1 
”;
$headers .= “From: newsletter@my_domain.com 
”;

mail($user, “Newsletter”, $out, $headers);
?>

We used a special Smarty method fetch() instead of display(). This method renders the template with variables and returns the rendered HTML to a variable. Though we need to send the newsletter, we have to capture the rendered output into a variable for further processing. That’s why we used fetch(). Then we used PHP’s built-in email sending capability to send this newsletter as an HTML mail.

Note

In the real world you shouldn’t send newsletters as HTML mails as many mail service providers do not support HTML mails and mails sent through them will be shown simply as plain text with HTML tags. Therefore, you should always send a plain-text copy to your users. The best practice is to ask users whether they want to receive HTML mails or plain text mails and send newsletters according to their choice.

Running PHP Code Inside your Templates

The main objective of Smarty is to separate the business logic layer from presentation layer. Therefore, a template should never contain business logic and the business logic layer should never contain HTML. Smarty is an extremely powerful templating language and gives you maximum flexibility as compared to other template engines. In Smarty, you can even run PHP code directly inside your template. Though this is not recommended, you may need it in some rare cases.

Smarty has a {php} tag. If you write PHP code inside a {php}{/php} tag block, it will be executed directly. Let’s see the following example:

php_code.tpl

{php}
echo “This is PHP Code executing directly<br />”;
for($i=0; $i<3; $i++)
echo “But it’s better to avoid embedding PHP code in your template<br />”;
{/php}

And here is the script to display it.

php_code.php

<?
include(“libs/smarty.class.php”);
$smarty = new smarty();
$smarty->display(“php_code.tpl”)
?>

If you run the script, you will see the following output. PHP codes are executed as usual.

Running PHP Code Inside your Templates

Note

Template programmers, you still you have the key in your hand. If you are worried about security and don’t want to allow some specific PHP functions from your templates, you can block them from being used. In the next chapter we will show you how.

..................Content has been hidden....................

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