Templating with PHP

Submitted by Rollie Hawk on Wed, 2005-06-29 16:20.

Whether you design websites for a living or just for fun, PHP can be a powerful tool. For those unfamiliar with it, PHP is a programming language that has made its mark primarily as a scripting tool for generating dynamic Web content. In addition to its ability to create interactive Web pages, PHP can be a useful time-saver when used to create a templating system for websites.

PHP templating can be done using one of three general methods: pulling the template into your content, pulling your content into the template, or pulling both content and templating into and single file. Even if you are a complete novice to programming, just a few short snippets of code can make your development life easier.

When is PHP Templating Worth Doing?

As long as your webserver is equipped with the PHP engine, you can use it to develop templates for anything you want. If you wanted, you could even code your entire site using PHP. But like any tool, there are times when it is much more useful than others.

Some scenarios that lend themselves to PHP templating are

  • when you want to template in a way that is invisible to the browser (unlike with frames and in-line frames),
  • when you want to be able to leave comments in files that can't be seen by anyone else,
  • when you want to leave a website that your customers and any future developers will be able to add to easily,
  • when you want a templating system that does not require third-party software such as Dreamweaver,
  • when you haven't made the final decision on the look of your pages but need to make content publicly available now,
  • or when you need to develop a complex site with different sections that will use variations on the same template.

Method 1 – Pulling the Template into your Content

Pulling your page template into already existing content pages is the easiest of the three methods. If your pages will all use exactly the same template, even if that template may be modified later, this may be all that you need.

Let's start out with a standard three-column layout. Please note that I am not including any extraneous HTML formating (this would probably be done using CSS anyway).

<html>
<head>
<title>your page's title</title>
</head>
<body>
<table>
<tr>
<td colspan="3">{your header}</td>
</tr>
<tr>
<td>{your left sidebar}</td>
<td>{your page's content}</td>
<td>{your right sidebar}</td>
</tr>
<tr>
<td colspan="3">{your footer}</td>
</tr>
</table>
</body>
</html>

We want to start by breaking this code into chunks. Everything that isn't considered "content" will be getting moved into its own PHP file. For the sake of simplicity, we'll consider everything in the HTML HEAD to be content, as well as the content section noted within the body.

We can break the non-content chunks up any way we choose. In this example, the most natural way is as a header, a left sidebar, a right sidebar, and a footer. Each chunk will have its own PHP file. For example, header.php might look like this:

<?PHP /* header.php */ ?>
echo '{Header images, text, etc.}';

You may notice that such a file isn't actually doing anything special with PHP. That's fine and doesn't have to, but we can always add more code later. The only reason we would want to use PHP as we just did is to keep comments from being pulled into the page when viewed by the browser.

Once we've created our four PHP files, our page's code will now look like this:

<html>
<head>
<title>your page's title</title>
</head>
<body>
<table>
<tr>
<td colspan="3"><?PHP include('header.php'); ?></td>
</tr>
<tr>
<td><?PHP include('leftcolumn.php'); ?></td>
<td>{your page's content}</td>
<td><?PHP include('rightcolumn.php'); ?></td>
</tr>
<tr>
<td colspan="3"><?PHP include('footer.php'); ?></td>
</tr>
</table>
</body>
</html>

Our new page won't do anything that the original didn't do, but it already has a couple of benefits. As our new template, we can edit the individual PHP files to change the look of all pages using this template without having to make changes to every content page. Also, we can place PHP comments within each file, allowing us to make notes or leave instructions that are invisible to anyone visiting our site. In fact, if someone decides to view the source code of this page, it will look exactly the same as it did before!

The primary drawback of this method is that it assumes your page will forever have the same general structure (e.g. three columns, one header, etc.). If that isn't the case, you'll want to try one of the others.

Method 2 – Pulling your Content into the Template

In this method, we'll be going the other direction by using a single template file. Where the first method was best for sites using a single template, this method is better for multiple templates. It also allows you to edit these templates without touching any content files.

You may be wondering, "Where will we be pulling this content from?" There is no single way to do this; content could be pulled from something as simple as a single text file or from something as complex as a MySQL database. To keep things simple for this example, we'll assume that page content is stored in individual files as variables. Such a file could look something like this:

<?PHP /* page1.php */
$pageTitle = 'Page 1\'s Title';
$pageContent = 'Page 1\'s Content';
?>

In this case, we will use two variables, $pageTitle and $pageContent, to pass content to our template. Those new to PHP should note the way I used the backslash to "escape" the single-quote character, allowing me to use it without delimiting my string in the wrong place.

We will access these variables using PHP's include() function in a slightly different way than in the first method. Our new page may look something like this:

<?PHP include('page1.php'); ?>
<html>
<head>
<title><?PHP echo $pageTitle; ?></title>
</head>
<body>
<table>
<tr>
<td colspan="3">{your header}</td>
</tr>
<tr>
<td>{your left sidebar}</td>
<td><?PHP echo $pageContent; ?></td>
<td>{your right sidebar}</td>
</tr>
<tr>
<td colspan="3">{your footer}</td>
</tr>
</table>
</body>
</html>

Did you notice how we used the include() function at the start of our template? This is because we are now passing information in the form of variables, rather than just passing HTML code. This allows use to break the content of a particular page into different chunks, similarly to the way be broke the templating elements into chunks before. This is useful because now we can place different types of content into different areas of our pages simply by using PHP's echo() function.

For example, let's say we need a nice, simple title above our page's main content. We can reuse one of our variables and edit our code so that

<td><?PHP echo $pageContent; ?></td>

becomes

<td>
<h2><?PHP echo $pageTitle; ?></h2>
<?PHP echo $pageContent; ?>
</td>

and we now have a title that will automatically appear at the top of all our content. This means we can use the template file we created for any page we want and only have to change the first line to reflect the content we want to pull into it.

The drawback of this method is that while content and design is completely separated, you have now doubled the number of files you will be storing because you will have to have both a template page and a content file for every individual page. The next method will accomplish same thing with much more efficiency.

Method 3 – Pulling both your Content and the Template into a Single File

If you liked the first two methods but need a more efficient structure to your pages, you'll want to try this method. But as any Perl programmer can tell you, efficiency is often bought at the cost of simplicity.

Let's start by expanding on our original example with a few more details. We'll assume a scenario where our site is collection of hundreds of pages, each belonging to one of a dozen sections. The header and footer is the same site-wide, but the three columns vary for each page. The middle column contains each page's unique content. The left sidebar displays information based on the section of the site it is part of. Finally, the right sidebar displays additional information about each page, such as the author's name and email address.

That's a lot of information, isn't it? Your head is probably spinning at the very thought of organizing all this! The bad news is that it will be somewhat complicated to set all of this up. The good news is that once this template is in place, adding new pages and new sections to our site will become a trivial process!

We're going to use a bit more PHP to drive all of this and we'll have to make several new files. To start with, we'll need a PHP file for each page's main content. This file will include, in the form of variables, every bit of information we need for each page. As an example example:

<?PHP /* page1.php */
$pageSection = 'Section 1';
$pageAuthorName = 'Author 5';
$pageAuthorEmail = 'author@somedomain.tld';
$pageTitle = 'Page 1\'s Title';
$pageContent = 'Page 1\'s Content';
?>

Are you wondering how we will tell our template which content file we need if we are only using a single file? One technique used by many content management systems (CMSs) is to pass a parameter through the URL. For example, if we want to show the content in page1.php, we could use the link http://somedomain.tld/index.php?p=1 where index.php is our main file. How this will work will be handled in a bit.

So that we see where this is all going, let's take a look at what index.php is going to look like when we are finished.

<?PHP /* index.php */
$pageNumber=$_GET['p'];
include('page'.$pageNumber.'.php');
include('header.php');
include('left.php');
include('main.php');
include('right.php);
include('footer.php');
?>

See how much cleaner that is? Using GET, we are pulling in a variable as a parameter in the URL. Of course, in a practical setting we'll want to have a default "home" page if there is no parameter and maybe even an error page for nonexistent pages. The first include will pull the appropriate file's content and place it into variables that we can use for in other PHP files.

To keep index.php looking clean, we'll cut up portions of our original sample page for use in each PHP file. For header.php, we'll include everything up to the place where we'll be showing the left sidebar. We'll also add our site's name and the new section name to the page title that will show at the top of the browser.

<?PHP /* header.php */ ?>
<html>
<head>
<title><?PHP echo 'The Site\'s Name - '.$pageSection.' - '.$pageTitle; ?></title>
</head>
<body>
<table>
<tr>
<td colspan="3">{your header}</td>
</tr>
<tr>
<td>

Where we made this cut looks a little abrupt since we left some tags open. That's okay since we'll be closing it later on. Including the opening <td> tag let's us keep left.php nice and readable, which is a good idea since it will be holding a lot of code.

Using the variable holding the section name, we'll generate the content of the left sidebar.

<?PHP /* left.php */
if ( $sectionName == 'Section 1' )
echo '{Section 1 stuff}';
if ( $sectionName == 'Section 2' )
echo '{Section 2 stuff}';
?>

For the next file, main.php, we'll close some of those HTML tags from before and display all the main page content. We'll include all the code up to the right sidebar just as we did with the left one.

<?PHP /* main.php */ ?>
</td>
<td>
<h2><?PHP echo $pageTitle; ?></h2>
<?PHP echo $pageContent; ?>
</td>
<td>

Just as before, that let's us keep our sidebar's code nice and clean. We don't need anything fancy for right.php, but keeping it readable will be useful if we ever make it more complex.

<?PHP /* right.php */
echo 'Author: '.$pageAuthorName.'<br />\n';
echo 'Email: '.$pageAuthorEmail;
?>

For footer.php, we'll need to close any and all open tags and display everything we want in out footer.

<?PHP /* footer.php */ ?>
</td>
</tr>
<tr>
<td colspan="3">{your footer}</td>
</tr>
</table>
</body>
</html>

If you didn't follow all of that, try pasting it all back together and see how each file works with the one before it. Though it's a lot of work to get such a templating system in place, you have the benefits of a very clean and modular index.php file, easily modified sidebars, and an easy system for adding new pages to your site.

What we've really made here is a very primitive CMS. If you or a client needs a new page added, just think how simple it will be to make a new page###.php file and add the fresh content to it. Even better, you could set up a nice script to generate fields for all the new page's content and format it for you, allowing clients to enter all the new content themselves before the script emails the full code to you. Not only will this make your job easier, but nobody will the wiser!

Final Notes

Those readers with strong programming backgrounds will almost certainly find other ways of performing the same PHP tasks presented above. That said, the examples were coded in the way they were so that they not only served the express purpose of this article, but also demonstrated some varied uses of PHP code that can easily be adapted by those new to the language.

Each of the three methods above has its place, depending on the purpose and structure of each site you make. If you find them particularly useful, be sure to adapt each one, or a combination of all three, into template template that you can use for every site you build from scratch. Believe me, the time you save in the long run will be well worth it.

References

The Home of PHP - http://www.php.net/
PHP Freaks - http://www.phpfreaks.com/

Note: This article originally appeared in Ping!Zine volume 3, issue 2.


( categories: Articles | Web Development )
Rollie Hawk is a consultant, web publisher, online personality, magazine writer, web developer, network administrator, teacher, husband and father residing in southern Illinois. He graduated in 2002 from Southern Illinois University, earning his BS majoring in math with a minor in chemistry.

Rollie is a certified math teacher with endorsements in chemistry, physics, and physical science and has taught students of all age groups and abilities, ranging from grade school to the university level. In addition to math and science, he has also taught GED, job skills, and alternative high school classes (his personal favorite).

After the birth of his daughter in 2004, Rollie decided to spend more time at home. This meant leaving his teaching position and devoting his working hours exclusively to consulting, web development, and general IT work.