19.5 Creating HTML Templates


You want to have things such as header files and table of contents automatically included, depending on the page.

Technique

Send filename to the page that you are currently on and include the corresponding file:

 <?php /* $filename is passed to the webpage */ ?> <html> <head>     <title> Somepage </title> </head> <body> <?php include("$filename.header"); ?> sometext <?php include("$filename.footer"); ?> </body> </html> 

Comments

Many people tend to forget that PHP is an embedded scripting language, meaning that you can embed PHP in HTML. Because of this, you can separate work that should be done by the designers ( mainly the HTML) and work that should be done by the programmers.

The include statement enables you to include PHP files that will be parsed and their output placed in the same place as the statement itself. If you want to include files that are in different languages and you have Apache, use the virtual() function (which is equivalent to <!--#include virtual...--> ). Consider the following example (using Perl as the other CGI language):

 yahoo.cgi #!/usr/bin/perl -w use strict; use LWP::Simple; print get 'http://www.yahoo.com'; yahoo.php <?php virtual("yahoo.cgi"); ?> 

This would print out the contents of the Yahoo home page. Please note that when you use this function with CGI scripts, you lose the speed advantage that PHP has over CGI scripts.

Alternately you can use PEAR's Template class which allows you to create a template with special "template" variables and then you can assign those variables values using the assign method and parse the template:

 SampleTemplate.htx <html> <head>     <title>%%PAGE_TITLE%%</title> </head> <body>   %%PAGE_BODY%% </body> </html> SampleProgram.php <?php // Template.php along with the template // class are from PEAR require_once("Template.php"); $templ = new Template("SampleTemplate.htx"); $templ->assign("PAGE_TITLE", "Hello World"); $templ->assign("PAGE_BODY",  "This is page contents"); print $templ->output(); ?> 


PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

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