Helping ordinary people create extraordinary websites!

How to make your own PHP template script

By Darren W. Hedlund
2005-03-16

How to make your own PHP template script
Many people ask how do you create a template system in PHP. It is true their are many different ways, but this will hopefully show you the basic understanding of this type of method.

First, let us understand the varibles in both the main .html page, and in the php scripts.
In this example <% main %> is the varible used in the main HTML template.

Next, the varibles in the index.php file are as follows:

1. $main
2. $content
3. $fd
4. $filename
5. $template
6. $action

The functions and commands within the index.php are as follows:

• function template();
• function home();
• fopen
• fclose
• global
• stripslashes
• eregi_replace
• echo
• switch
• default:
• break:

This type of scripting will make outputed varible $main match up with HTML <% main %>. The result is that you can output just about anything within a template.

Now, create three files (named below).

Filename: theme.htm

<html><body>
<table cellpadding="0" spacepadding="0" border="0">
<tr><td valign=top align=left>
<% main %>
</td></tr>
</table>
</body>
</html>


Filename: index.php

<?

function template($content) {
global $main;
$filename = "theme.htm";

if(!$fd = fopen($filename, "r")) {
$error = 1;
}
else {
$template = fread ($fd, filesize ($filename));
fclose ($fd);
$template = stripslashes($template);
$template = eregi_replace("<% main %>", "$main", $template);
$template = eregi_replace("<% content %>", "$content", $template);
echo "$template";
} }


function home() {
global $main;
include ("test.php");
template("$data");
}


switch($action) {
default: // default switch
home();
break;
}
?>

Filename: test.php

<?
$main .= 'This is a test of the emergency boradcast system.<br>This is only a test';
?>


Notice the test.php file having the $main .=. This would be normally an echo command, but echo is not longer needed, since it would not stream through the index.php in the <% main %> area of the template HTML file.

You can add more than one varible such as $main or <% main %>.



Tutorial pages:
  • How to make your own PHP template script

 2 Votes

You might also want to check these out:


Leave a Comment on "How to make your own PHP template script"
You must be logged in to post a comment.

Link to This Tutorial Page!


GET OUR NEWSLETTERS