How to Make Your Own PHP Template

free php tutorials, php classes, php utilities, free tools

A PHP template can seperate your php and html, it is an easy way too create big sites without much hassle in maintaining a consistent look

HOw to create your own template system using php? there are different way to create template system but in this tutorial we will define a simple way to create php template system.

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 : if you are familiar you know about fopen, it can open any type of file.
  • fclose : this function can clos any file
  • global : we use some global variables to do this work
  • stripslashes
  • eregi_replace : this function can replace any string with existing word/character
  • echo : it is used for output

We also need to use some control structure to make php template system

  • 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 We create 3 files

  1. template.htm
  2. index.php
  3. output.php

Now lets write code template.htm

<html><body>
<table width="100%">
<tr><td align=left>
<% main %>
</td></tr>
</table>
</body>
</html>

Now we will write code for index.php, it contains php template function

<?
function template($content) {
  global $main;
   $filename = "template.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 ("output.php");
template("$data");
}
switch($action) {
        default:  // default switch
        home();
        break;
}
?>

Now we will test it in output.php

<?
$main .= 'This is a test of php template system.<br / >check it ';
?>

Notice the output.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 %>.

Bookmark This Page