Do not create a parser as completely meaningless, PHP is already a template engine, all you want to do is expand its capabilities with an encapsulated template system.
Below is the way that I always create my template engine, I lose it very much and can be expanded with the help of template assistants as such.
The good thing about my template system is that you don’t have to spend your resources creating a caching system for compiled templates, as they are already in a compiled state, compared to engines like smarty.
First, we want to create a basic template class that will be used to set data, select a template, etc.
So let's start with this:
class Template { private $__data = array(); public function __construct(){} public function __set($key,$val) { $this->__data[$key] => $val; } public function __get($key) { return $this->__data[$key]; } public function Display($Template) { new TemplatePage($Template,$this->__data);
this is a very simple class that will allow you to do something like
$Template = new Template(); $Template->Userdata = $User->GetUserData(); $Template->Display("frontend/index");
Now you might notice the class above called TemplatePage , this is the class that loads the actual file template, and inside the actual template you fall into the TemplatePage area.
This will allow you to have methods for retrieving your template data and accessing helpers, below is an example of TemplatePage
class TemplatePage { private $__data = array(); public function __construct($template,$data) { $this->__data = $data; unset($data); //Load the templates if(file_exists(TEMPLATE_PATH . "/" . $template . ".php")) { require_once TEMPLATE_PATH . "/" . $template . ".php"; return; } trigger_error("Template does not exists",E_USER_ERROR); } public function __get($key) { return $this->__data[$key]; } public function require($template) { if(file_exists(TEMPLATE_PATH . "/" . $template . ".php")) { require_once TEMPLATE_PATH . "/" . $template . ".php"; return; } trigger_error("Template does not exists",E_USER_NOTICE); } public function link($link,$title) { return sprintf('<a href="%s">%s</a>',$link,$title); } }
So now that the template is loaded into the scope of the class, you can extend methods like link and require to have a fully functional set of template tools
Template example:
<?php $this->require("folder/js_modules") ?> <ul> <?php foreach ($this->photos as $photo): ?> <li> <?php echo $this->link($photo->link,"click to view") ?> <span><?php echo $photo->image_name?></span> </li> <?php endforeach; ?> </ul> <?php $this->require("folder/footer") ?>