24 January, 2010

Make Your Own Templating Engine

You can make your own templating engine easily. May be you can't add all facilities of other popular frameworks but it will help you to know something new.

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_templete
{
    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";}
    }   
}

Add PHP tag in it.
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");
$templete = new eshan_templete();
$templete->assign("hello","hello world");
$templete->display("index.tpl");
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.

No comments:

Post a Comment