README.md
December 5, 2022 · View on GitHub
Description
The purpose of this tutorial is to show you how to implement a simple class to handle page templates.
More Info
| Submitted On | |
| By | Daniel M. Hendricks |
| Level | Beginner |
| User Rating | 4.4 (79 globes from 18 users) |
| Compatibility | PHP 4.0 |
| Category | Controls/ Forms/ Dialogs/ Menus |
| World | PHP |
| Archive File |
Source Code
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.