PDA

View Full Version : Template engine with PHP



admans
07-18-2005, 17:55 PM
How to use PHP to make a template system with static header/footer.

Abstract:
First we assume that we have a root folder and that all the files we need are in it.
Let's say that we have header.html, footer.html, content1.html, content2.php, main.html, and finally error.html.
Our goal is to use static header (header.html) and footer (footer.html) while the content in between is changing (content1.html, content2.php, main.html).
In the case where no page is selected the main page (main.html) will be displayed by default and if the name does not exist it will display the error page (error.html).
Notice that the content page as we name it can be HTML or PHP.

PHP Code:
The file that is used for the template system is called index.php and contains the following code:


<?php

/*--TEMPLATE HEADER--*/

include_once("header.html");

/*--TEMPLATE CONTENT--*/

// Default page main.html
// If does not exist error.html

if(!isset($_GET['page'])){
include_once('main.html');
} else {
$pagename = $_GET['page'];
switch($pagename)
{
case content1:
$page = "content1.html";
break;
case content2:
$page = "content2.php";
break;
default:
$page = "error.html";
}
include_once($page);
}



/*--TEMPLATE FOOTER--*/

include_once("footer.html");

?>

You can add as many page as you want by adding some cases to the switch() function.

Example:


case whatever:
$page = "whatever.php";
break;

This code can be repeated infinitely as long as the name is unique.

Browsing URL's
Once everything is ready and uploaded to your server web space, you can call any page you want by using:
index.php?page=pagename. In our example above it will be index.php?page=whatever. If you give a page name that does not exist, it will automatically forward you to error.html and if you go directly to the index.php page, it will display main.html by default.



Source Script by my friend: o0slowpaul0o
Pleas keep his copyright in the footer.Got permission from him to post this topic.

xyris
07-19-2005, 07:07 AM
We will jsut need to add this to every page?