Creating a Basic PHP Template Engine

Creating a Basic PHP Template Engine

Date: 25 August 2011  |  Posted by admin  |  Category: ,

PHP is a templating engine but the syntax is just plain ugly as a template language. For several years now, We have been promoting web development best practices, and one of them is the separation of concerns by following MVC architecture. It certainly helps when we have big projects where many people need to work together. The developers work on the code (Controller and Model) and the web designers work on the template. In this tutorial I am going to teach you in depth on creating a simple php template engine.

Before we can start we need a .php document lets name it basic.template.php, now we can start coding.

First we need to declare our Template class:

class basicTemplate
{
// rest of the code 
}

Remember the class name we will to use it later to call the class. Lets move onto the class variables:

var $Template; // Current Templates Name. 
var $TemplateExt = '.tpl'; // Templates File extension. 
var $TemplateDir = './templates/'; // Our Template Directory. 

We will use .tpl as our template extension, for example header.tpl or footer.tpl. Lets create a function to select a template file.

function SelectTemplateFile($file, $error_line = 0, $erro_file = '') 
    { 
        if(is_dir($this->TemplateDir)) // If the $templatedir exsits. 
        { 
            if(!file_exists($this->TemplateDir.$file.$this->TemplateExt))  
            { 
                $error = "<b>File:</b> ".$erro_file."<br/> 
                <b>Line:</b> ".$error_line."<br/> 
                <b>Date:</b> ".date("D M j G:i Y")."<br/><br/> 
                Error loading ".$this->TemplateDir.$file.$this->TemplateExt.",
file not found."; 
                return die($error); // Returns $error. 
            } 
            elseif(file_exists($this->TemplateDir.$file.$this->TemplateExt))  
            { 
                return $this->Template=file_get_contents($this->TemplateDir
.$file.$this->TemplateExt); 
            } 
        } 
        elseif(!is_dir($this->TemplateDir)) // Else If the directory does not exsit. 
        { 
                $error = "<b>File:</b> ".$erro_file."<br/> 
                <b>Line:</b> ".$error_line."<br/> 
                <b>Date:</b> ".date("D M j G:i Y")."<br/><br/> 
                Error opening ".$this->TemplateDir.", directory does not exist."; 
                return die($error); // Returns $error. 
        } 
    } 

This function select a template filename and check if the filename and template directory exist then get the file by using file_get_contents function. We have also added a code that will generate errors if the template file or directory does not exist. Now lets create a function that will replace variables to the template file.

    function ReplaceVars($vars=array(), $error_line = 0, $erro_file = '') 
    { 
        if (sizeof($vars) > 0) // If the array of vars is not emtpy. 
        { 
            foreach ($vars as $var => $content) // Loops through the array. 
            { 
                $this->Template=str_replace("{".$var."}", $content, $this->Template); 
            } // End Foreach. 
        } 
        else // Else the array of vars is empty. 
        { 
            $error = "<b>File:</b> ".$erro_file."<br/> 
            <b>Line:</b> ".$error_line."<br/> 
            <b>Date:</b> ".date("D M j G:i Y")."<br/><br/> 
            Error no tags destined for replacement."; 
            return die($error); 
        } 
    }  

This function find and replace the tags that we have defined. It also generates error if there is no tags defined. Now to the final function this will compile the entire template and display it.

function Compile() 
    { 
        eval("?>".$this->Template."<?"); 
    } 

Using eval instead of just a return will allow us to use php directly inside the tpl file. So lets move to using the template engine!

<?php 
require_once("basic.template.php");  
$TemplateEngine = new basicTemplateEngine; // This calls our TemplateEngine class. 
$TemplateEngine->SelectTemplateFile('example', __LINE__, __FILE__); // load example.tpl 
$TemplateEngine->ReplaceVars(array( 
'name' => 'John', 
'message' => 'this is an example on using a basic template engine<br/>pretty easy.' 
), __LINE__, __FILE__); 
$TemplateEngine->Compile(); 
?>

Now lets create a file called example.tpl and place it in your templates directory.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Basic Template Engine Test</title>
</head>
<body>
Hello {name}!
{message}
</body>
</html>

See the {name} and {message} tags, these will be replaced using our ReplaceVars function, if you want to add new tags just simply define them on the .tpl file {tag} and in the array add a new tag name and replacement: "tag"=> 'Replace Me', and you now have a simple PHP Template Engine!

Here is the full code: basic.template.php

<?php 
class basicTemplateEngine 

    var $Template; // Current Templates Name. 
    var $TemplateExt = '.tpl'; // Templates File extension. 
    var $TemplateDir = './templates/'; // Our Templates Directory. 
     
    function SelectTemplateFile($file, $error_line = 0, $erro_file = '') 
    { 
        if(is_dir($this->TemplateDir)) // If the $templatedir exsits. 
        { 
            if(!file_exists($this->TemplateDir.$file.$this->TemplateExt)) 
            { 
                $error = "<b>File:</b> ".$erro_file."<br/> 
                <b>Line:</b> ".$error_line."<br/> 
                <b>Date:</b> ".date("D M j G:i Y")."<br/><br/> 
                Error loading ".$this->TemplateDir.$file.$this->TemplateExt.",
file not found."; 
                return die($error); 
            } 
            elseif(file_exists($this->TemplateDir.$file.$this->TemplateExt)) 
            { 
                return $this->Template=file_get_contents($this->TemplateDir.
$file.$this->TemplateExt); 
            } // End ElseIf. 
        } 
        elseif(!is_dir($this->TemplateDir))  
        { 
                $error = "<b>File:</b> ".$erro_file."<br/> 
                <b>Line:</b> ".$error_line."<br/> 
                <b>Date:</b> ".date("D M j G:i Y")."<br/><br/> 
                Error opening ".$this->TemplateDir.", directory does not exist."; 
                return die($error); // Returns $error. 
        } // End ElseIf. 
    } // End Function. 
     
    function ReplaceVars($vars=array(), $error_line = 0, $erro_file = '') 
    { 
        if (sizeof($vars) > 0) // If the array of vars is not emtpy. 
        { 
            foreach ($vars as $var => $content) // Loops through the array. 
            { 
                $this->Template=str_replace("{".$var."}", $content, $this->Template); 
            }  
        } 
        else // Else the array of vars is empty 
        { 
            $error = "<b>File:</b> ".$erro_file."<br/> 
            <b>Line:</b> ".$error_line."<br/> 
            <b>Date:</b> ".date("D M j G:i Y")."<br/><br/> 
            Error no tags destined for replacemnt."; 
            return die($error); // Returns $error. 
        } // End Else. 
    } // End Function. 
     
    function Compile() 
    { 
        eval("?>".$this->Template."<?");  
    } 
}  
?> 

That's it. Enjoy and Have Fun!

18 Comments

  1. (27 days ago)
    Excellent tutorial, really helpful in understanding how php template engines work
  2. (5 months ago)
    Hey mate you keep the comment on my post so I tried linking it back. Thanks in advace
  3. (5 months ago)
    That would be good for somebody who likes to learn basic idea in PHP. Thanks in advance
  4. (8 months ago)
    pejkldzgfsxfc, http://www.fxzbabypfs.com wtwpoqfvuq
  5. (8 months ago)
    edfhxdzgfsxfc, <a href="http://www.pifkndqoaa.com">ubfhcenmbz</a> , [url=http://www.dcyufkhfor.com]vzvvqdbhte[/url], http://www.tuknsxhwnj.com ubfhcenmbz
  6. (8 months ago)
    In it something is. Now all became clear, many thanks for the help in this question.
  7. (8 months ago)
    Thanx with the energy, sustain the great function Excellent perform, I'm likely to begin a little Weblog Engine training course function utilizing your internet site I am hoping you get pleasure from running a blog with all the common BlogEngine.web.Thethoughts you express are actually brilliant. Wish you may proper some far more posts.
  8. (8 months ago)
    Thanx for your hard work, sustain the great function Wonderful operate, I'm planning to commence a little Weblog Engine training course operate utilizing your internet site I really hope you appreciate running a blog with all the well-liked BlogEngine.web.Thethoughts you express are truly great. Desire you are going to appropriate some far more posts.
  9. (8 months ago)
    It is a superb ideas specially to these new to blogosphere, quick and correct information… Many thanks for sharing this 1. A should study write-up.
  10. (8 months ago)
    Greetings! Extremely useful suggestions on this informative article! It truly is the minor modifications that make the greatest alterations. Many thanks a good deal for sharing!

Post Comment

RSS feed for comments on this page | RSS feed for all comments

TrackBacks

Trackback URL for this page.