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.

01 January, 2010

Happy New Year

Happy New Year

 

PHP
  1. echo "Happy New Year";
PYTHON
  1. print("Happy New Year")
C#
  1. Using System;
  2. class Program
  3. {
  4.      static void Main(string[] args)
  5.      {
  6.           Console.WriteLine("Happy New Year");
  7.      }
  8. }
JAVA 
  1. class Program
  2. {
  3.    public static void main(String args[])
  4.    {
  5.         System.out.print("Happy New Year");
  6.    }
  7. }
C
  1. main()
  2. {
  3.     printf("Happy New Year");
  4. }