Section 10.2. Templates


10.2. Templates

Templates separate the HTML code that defines the presentation or look of a page from the PHP code that's responsible for gathering the data. Once separated, it becomes easier for someone with HTML and perhaps CSS knowledge to modify the template without worrying about breaking the PHP code. Likewise, the PHP code can focus on the data instead of getting caught up in presentation details.

There are other advantages to using templates, too. If you make a mistake in the template, the error will be clearly returned from the template. The template itself can generally be loaded into a web browser or a graphical web development tool such as Dreamweaver, since it resembles the final state of the page when processed. Templates support very basic programming features for use with presentation, such as being able to tell whether a section of a page should be visible.

Of course, nothing's perfect; there are a couple of disadvantages to templates. Templates increase the number of files to maintain. They add a small amount of extra processing time. They also require installing the template engine and setting up directories. You need to be running at least PHP Version 4.0.6 to use Smarty, a popular template engine.

10.2.1. Template Engine

There are several template packages available on the Internet. Each uses its own template engine to process the templates and make them as efficient as possible. No matter which template engine you use, you'll always follow the same basic steps:

  1. Retrieve your data.

  2. Make calls to the template functions for each value that's used in a template.

  3. Display the template using the template function.

We'll walk through this process with some examples shortly. One of the more popular template engines available is Smarty, shown in Figure 10-16. Smarty has many, many features, but what we're concerned most with is the basic template engine functionality.

Figure 10-16. Smarty template engine


10.2.2. Installation

While installing Smarty isn't as complex as installing and configuring Apache, PHP, and MySQL, it still deserves some attention.

  1. Smarty can be downloaded from http://smarty.php.net/download.php. Download the latest stable release.

  2. Extract the contents of the Smarty file to a convenient location.

  3. Create a directory called Smarty in your document root. If you don't know what your document root is, you can use PHP to find out:

     <?php echo $_SERVER["DOCUMENT_ROOT"]; ?> 

  4. Copy the contents of Smarty's libs/ directory from the directory you extracted it to into the Smarty directory you just created.

  5. You should now have the following file structure in your document root:

    Smarty/Config_File.class.php

    Smarty/debug.tpl

    Smarty/internals/

    Smarty/plugins/

    Smarty/Smarty.class.php

    Smarty/Smarty_Compiler.class.php

10.2.2.1. Application level directories

For each application with which you wish to use Smarty, you'll need to set up a set of four directories. The four directories are for templates, compiled templates, cached templates, and configuration files. Although you may not use all of those features, you should set up the directories just in case.

  1. Create a directory called myapp/ in your document root. (You can call it whatever you want, but for the remainder of the text, we will refer to it as myapp/.)

  2. Create a directory named smarty inside the directory you just created (myapp/smarty).

  3. In the smarty directory you just created, create four more directories: templates, templates_c, cache, and config. Ensure that the web server will have write access to the templates_c and cache directories that you created in the previous step.

All you need to do is create a template and a PHP file to try it out.

10.2.2.2. Creating sample scripts

Now set up your application in the document root. See Example 10-11.

Example 10-11. The index.php file to create

 ?php // use the absolute path for Smarty.class.php require($_SERVER["DOCUMENT_ROOT"].'/Smarty/Smarty.class.php'); $smarty = new Smarty(); $smarty->template_dir = $_SERVER["DOCUMENT_ROOT"].'/myapp/smarty/templates'; $smarty->compile_dir = $_SERVER["DOCUMENT_ROOT"].'/myapp/smarty/templates_c'; $smarty->cache_dir = $_SERVER["DOCUMENT_ROOT"].'/myapp/smarty/cache'; $smarty->config_dir = $_SERVER["DOCUMENT_ROOT"].'/myapp/smarty/configs'; ?> 

The bulk of what's happening in Example 10-11 is telling your PHP program where to find the Smarty class file to include and the location of the application directories.

Next, create myapp/index.php:

 <?php require_once("smarty.php"); $smarty->assign('test', '123'); $smarty->display('index.tpl'); ?> 

10.2.2.3. Create a sample template

Edit the index.tpl file in your myapp/smarty/templates directory, as shown in Example 10-12.

Example 10-12. The sample index.tpl template to create

 <html> <head> <title>Smarty</title> </head> <body> It's as easy as {$test}. </body> </html> 

Now, go to your new application through the web browser (http://www.domain.com/myapp/index.php, in our example). You should see something like Figure 10-17.

Figure 10-17. Web browser-displayed code


Now you can convert the previous example to the version shown in Example 10-13.

Example 10-13. Using the template to display the table

 <?php function query_db($qstring){ require_once("smarty.php"); require_once("db_login.php"); require_once("DB.php"); $connection = DB::connect("mysql://$db_username:$db_password@$db_host/$db_database"); if (DB::isError($connection)){ die("Could not connect to the database: <br />". DB::errorMessage($connection)); } $query = "SELECT * FROM `books` NATURAL JOIN `authors` WHERE `books`.`title` like '%$qstring%'"; $result = $connection->query($query); if (DB::isError($result)){ die ("Could not query the database: <br>". $query. " ".DB::errorMessage($result)); } while ($result_row = $result->fetchRow(DB_FETCHMODE_ASSOC)) { $test[] = $result_row; } $connection->disconnect(); $smarty->assign('users', $test); $smarty->display('index2.tpl'); } ?> <html> <head> <title>Building a Form</title> </head> <body> <?php $search = $_GET["search"]; $self = $_SERVER['PHP_SELF']; if ($search != NULL){ echo "The search string is: <strong>$search</strong>."; query_db($search); } else { echo ' <form action="'.$self.'" method="GET"> <label> Search: <input type="text" name="search"  /> </label> <input type="submit" value="Go!"> </form>'; } ?> </body> </html> 

The template is a bit more complex, since you're dealing with rows coming back in arrays and there are multiple rows.

The index2.tpl file is shown in Example 10-14.

Example 10-14. The new table template

 <table border=1> <tr><th>Title</th><th>Author</th><th>Pages</th></tr> {section name=mysec loop=$users}   {strip}   <tr>     <td>{$users[mysec].title}</td>     <td>{$users[mysec].author}</td>     <td>{$users[mysec].pages}</td>   </tr>   {/strip} {/section} </table> 

Example 10-14 outputs the screen shown in Figure 10-18.

Figure 10-18. The output doesn't change even though you're using the template


The template incorporates the looping element of Smarty. We used an associative array for returning your results to make the template easier to read, as the field names are the column names and not numbers. Smarty could have easily added some nice decorations, such as alternating the color of the row backgrounds.

In the next chapter, we'll discuss more complicated database functions now that you have a good solid understanding of database functions.



Learning PHP and MySQL
Learning PHP and MySQL
ISBN: 0596101104
EAN: 2147483647
Year: N/A
Pages: 135

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net