Basic PHP Template System
Posted by Pete | Posted in PHP Functions, PHP Tutorials | Posted on 20-10-2009-05-2008
0
In this tutorial we will learn how to make a basic php template system. Which will allow us to include the template files into our php code.
So first lets define where and what our template files are called and where they are stored.
DEFINE("TEMPLATE_DIR", "/"); // Set Templates Directory DEFINE("TEMPLATE_EXT", ".tpl"); // Set Template Files Extension
Now we have the defined details we need to actually retrieve the template file
function get_temp($file){ // Start get_temp function with $file variable. if(file_exists(TEMPLATE_DIR . $file . TEMPLATE_EXT)){ // Get both the template directory and extension and the file name then check if it exists. $temp = file_get_contents(TEMPLATE_DIR . $file . TEMPLATE_EXT); // If it exists get the contents of the file return $temp; // Return $temp }else{ // If it doesnt exist display error message return false; } }
And finally we have to parse the template and replace the desired text with the replacement text.
function parse_temp($file, $array){ // Start parse_temp function with 2 variables, file and array. $temp = get_temp($file); // Run the get_temp function with the file name passed to the parse_temp function. if($temp){ foreach ($array as $key => $value){ // Go through each array $temp = str_replace($key, $value, $temp); // Replace $key with $value in the template file } }else{ // If $temp is empty or false echo "\"" . TEMPLATE_DIR . $file . TEMPLATE_EXT . "\" Does Not Exist."; // Show error message } return $temp; // Return temp }
So now we have it built lets see how we can use it
welcome.tpl
Name: {first_name} {last_name}<br/>
Address: {address}example.php
$variables = array("{first_name}" => "Peter", "{last_name}" => "Kelly", "{address}" => "52 Blahblah lane"); echo parse_temp("welcome", $variables);
So there you have it your very own template system. Any questions or feedback please leave a comment.


