Important alert: (current site time 10/31/2014 1:01:13 AM EDT)
 

article

Simple PHP Template Class Example

Email
Submitted on: 7/26/2004 1:31:36 PM
By: Daniel M. Hendricks  
Level: Beginner
User Rating: By 18 Users
Compatibility: PHP 4.0
Views: 118785
author picture
(About the author)
 
     The purpose of this tutorial is to show you how to implement a simple class to handle page templates.

 
 
Terms of Agreement:   
By using this article, you agree to the following terms...   
  1. You may use this article in your own programs (and may compile it into a program and distribute it in compiled format for languages that allow it) freely and with no charge.
  2. You MAY NOT redistribute this article (for example to a web site) without written permission from the original author. Failure to do so is a violation of copyright laws.   
  3. You may link to this article from another website, but ONLY if it is not wrapped in a frame. 
  4. You will abide by any additional copyright restrictions which the author may have placed in the article or article's description.
				

Simple PHP Template Class

The purpose of this tutorial is to show you how to implement a simple class to handle page templates.  It can be extended in any way you wish.

The Class (template.class.php)

<?
class Template {
   public $template;
   function load($filepath) {
      $this->template = file_get_contents($filepath);
   }
   function replace($var, $content) {
      $this->template = str_replace("#$var#", $content, $this->template);
   }
   function publish() {
      eval("?>".$this->template."<?");
   }
}
?>

The Template File (design.html)

This file will contain the design of your web site and the blank fields that will be merged with content data.

<html>
<head>
<title>#title#</title>
</head>
<body>
<h3>Hello #name#!</h3>
<p>The time is: #datetime#</p>
<? echo "<p>Embedded PHP works too!</p>"; ?>
</body>
</html>

Usage (index.php)

Now we will create a script that load the template and use the class to merge the data.

<?
include "template.class.php";

$template = new Template;
$template->load("design.html");
$template->replace("title", "My Template Class");
$template->replace("name", "William");
$template->replace("datetime", date("m/d/y"));
$template->publish();
?>

When you run the above script, index.php, it will output the following:

 <html>
<head>
<title>My Template Class</title>
</head>
<body>
<h3>Hello William!</h3>
<p>The time is: 03/10/04</p>
<p>Embedded PHP works too!</p>
</body>
</html>

This code, as you can see, is very simple.  It supports embedding PHP into the original template file (design.html).  You could easily extend it to pull data from a database such as MySQL.


Other 12 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments

7/29/2004 10:44:39 PM

Not sure why...but had to change public to var for this code to work.
(If this comment was disrespectful, please report it.)

 
7/30/2004 10:40:46 AMiwan

it's because the code is in php5. and i assume you use php4.x which does not support public/private types. By the way, there are ready to use template systems like this, "smarty" for example.
(If this comment was disrespectful, please report it.)

 
8/1/2004 11:06:27 AMDaniel M. Hendricks

Yes, but Smarty is so bloated. I just wanted something simple to merge a page with variables. Smarty is a lot of code to do that, and I've had problems with Smarty's unusual way of caching the design, particularly when I move web hosts. Sometimes the directory will become unreadable and I have to delete it to have it create another.
(If this comment was disrespectful, please report it.)

 
3/1/2005 9:57:32 AMDanny Pryor

Well thats strange then because I have php5 and i had to change it also before it would work.
(If this comment was disrespectful, please report it.)

 
5/3/2005 6:29:19 AMDanny Pryor

I just wanted to say ...... many thanks for this simple templating system. It was short , simple
(If this comment was disrespectful, please report it.)

 
5/25/2005 5:27:36 AMrsxx

Thank You Very Much! Simple and to the point and just what I needed! Greatly Appreciated! Also I had to change "public" to "var" as well.
(If this comment was disrespectful, please report it.)

 
8/31/2005 3:48:57 PMDigiOz Multimedia

Hello Daniel,

That is the BEST and SIMPLEST explaination of template driven PHP code that I have ever read anywhere! I have also read some of your other posts on planet source code and they all Rock! (Specially the JSP / MySQL Tutorial)

Keep up the good work my friend, and thanks again. :D

Pete


(If this comment was disrespectful, please report it.)

 
10/4/2005 10:32:20 AM

Brilliant code. I'm trying to understand the simplicity behind the line: eval("?>".$this->template."
(If this comment was disrespectful, please report it.)

 
12/9/2006 11:37:34 AMjose

Excellent
(If this comment was disrespectful, please report it.)

 
2/27/2007 1:59:16 PM

This was a very good exercise. One of the few that lends itself to practical usage.....
(If this comment was disrespectful, please report it.)

 
10/11/2007 10:02:12 PMEvan

Very well done, not a lot of extra talking. Simple and just what I needed. Thanks! :)
(If this comment was disrespectful, please report it.)

 
10/22/2008 9:15:25 AMMartin Tonek

Simple and neet.. this what i needed! Thanks mate.
(If this comment was disrespectful, please report it.)

 
8/6/2010 7:44:28 PMGF

There is a litle securoty problem. HTML: PHP: $template->replace("uname", $_POST['user']); The user suplyed code will be evaluated. Change # to something more uncommon like {#} Add this function clear() { $this->template = preg_replace('[{#}(.*){#}]', "", $this->template); } and call before publish, it will remove all the unused variables. Peace, GF
(If this comment was disrespectful, please report it.)

 
8/31/2011 5:40:49 AMLouis

Fantastic! Really nice clean example!
(If this comment was disrespectful, please report it.)

 
2/13/2012 3:28:20 AMNick Lachey

Fantastic post. Here’s a tool that lets your build your online database without programming. There is no need to hand code PHP. Cut your development time by 90%
http://www.caspio.com/
(If this comment was disrespectful, please report it.)

 
7/6/2012 7:09:00 AMwisga

very useful tutorial for me. I am trying on modifying the code to display some looping row of data. The problem is that I still can't find a way to grab the html content between a particular container, (in this context, I use html comment and to contain the looping section), and then replace the contained part with rows of data. Is it possible to make? Really need your assistance and thank you for writing the article :D
(If this comment was disrespectful, please report it.)

 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.