article

Simple PHP Template Class Example

Email
Submitted on: 1/1/2015 11:53:00 PM
By: Daniel M. Hendricks (from psc cd)  
Level: Beginner
User Rating: By 18 Users
Compatibility: PHP 4.0
Views: 1064
 
     The purpose of this tutorial is to show you how to implement a simple class to handle page templates.

 
				

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 8 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


 There are no comments on this submission.
 

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.