Quick and Simple Template System in PHP
Quick and Simple Template System in PHP
Template systems are increasingly popular among PHP developers mainly because they provide a clean way to design templates. However there is nothing better than using PHP directly in the template files. But not everyone is of this opinion. For this reason, today we will be covering a very simply PHP class that you can use to generate clean template files. Let's start.
Define our Main PHP Class
The core of this class is to open a file and scan it then store all of the new content in a protected variable that will be use throughout the class. Are you ready to see the simple PHP class that allows you to achieve this? Are you sure? Here it is:class Template{
protected $content;
public function __construct(){}
// Open the file and store the content
public function file($name){
if(!file_exists($name)) die("Template file is not reachable.");
$this->content = file_get_contents($name);
}
// Render the final content
public function render(){
echo $this->content;
unset($this->content);
}
// Assign variables
public function assign($var,$val){
$this->content = str_replace('{'.$var.'}', $val, $this->content);
}
}
Okay so now you might say how do I use this amazingly simply PHP class. Well here is how.
1. Include the PHP Class
require("Template.class.php");
2. Instantiate the Template Class
$template = new Template();
3. Open theme file
$template->file("demo.tpl");
4. Assign PHP variables
$template->assign("title", "My Page Title");
5. Render the template file
$template->render();
6. Set your template file
Your template file can be in any format. It doesn't matter as long as you use the proper short code format. Here is what the demo.tpl file looks like in the example above:<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>{title}</title>
</head>
<body>
My page title is {title}
</body>
</html>
And this how it will output once you render the template
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>My Page Title</title> </head> <body> My page title is My Page Title </body> </html>So that is it for this incredible difficult (*sarcasm*) tutorial. Now go ahead and use it for your simple projects. You don't need smarty or any other templating system. These 20 lines will save you a lot of work.