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!
<?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!
[...]Creating a Basic PHP Template Engine » Cyferweb - Digital Solutions[...]
Creating a Basic PHP Template Engine
Creating a Basic PHP Template Engine
Creating a Basic PHP Template Engine
1 2 next »