Eastern Michigan University EMU HOME
 
people.emich.edu
About people.emich.edu
Tips & Resources
Print this page
people.emich.edu

Introduction to PHP: Templates

Today, there is no such thing as a simple web page. People expect pages to look and function consistently, which is difficult to do with static HTML. For example, let's say you have a small site of only five pages. Each page has the same navigation bar. One day one link in the navigation bar changes, so you need to update all five pages. You make the change on the first page, and carefully copy the changes to the next page. Right around the third page you wish you didn't have to do this. Does that sound familiar?

There is a better way. Using PHP, you can paste the navigation bar into its own file and call it, say, navbar. Then, you can change your documents to include navbar every time the page is loaded, by replacing the navigation bar HTML with the following line.

    <?php readfile("navbar"); ?>

Next time you have to change the navigation bar, you only need to update one file and you are done.

In fact, this page was constructed using this method. I started out with a template HTML document. I copied everything above the main text area and pasted it into a file I called header.html, and everything below it into another file called footer.html, and put both files in a folder called common.d. Then, each new page I created I started with

    <?php readfile("common.d/header.html"); ?>

and ended with

    <?php readfile("common.d/footer.html"); ?>

filling the middle with HTML content. This allowed me to quickly create new pages with a consistent look and feel. Furthermore, it allows me to update the way every page looks by changing the appropriate template file.

If you need your template files to contain PHP code, you will need to use the include() function instead of the readfile() function.

Next: Conclusion




EMU Home | Contact EMU | Site Map | Directories | Calendars | My.emich | Search