Today I will show you how to write a simple templating engine..
First make a PHP Class which is the heart of our templating engine. Make a file named template.class.php . Now write the code shown below..
class eshan_templeteAdd PHP tag in it.
{
private $array_var = array();
private $array_item = array();
public function __construct($assign = false,$display = false)
{
if ($assign){$this->assign($assign);}
if ($display){$this->load($display);}
}
public function assign($var,$item = false)
{
if (is_array($var))
{
foreach ($var as $a=>$b)
{
$this->array_var[] = '{$'.$a.'}';
$this->array_item[] = $b;
}
}
else {$this->array_var[] = '{$'.$var.'}';$this->array_item[] = $item;}
}
public function display($file)
{
if (file_exists($file))
{
echo str_replace($this->array_var,$this->array_item,file_get_contents($file));
}
else {echo "Templete not found";}
}
}
Now make a file named index.tpl . Now write html code in it. Add a PHP variable in it after body. Like [body]{$hello}[/body]. Replace '[' with '<' and replace ']' with '>' .
Now make a file named index.php. Write the code shown below..
include_once("template.clas.php");Now study it. It is one of the most simple templating engine. If it help you then donate some money to help the people of Haiti.
$templete = new eshan_templete();
$templete->assign("hello","hello world");
$templete->display("index.tpl");