PHP - Simple Template Engine Part 1

In this two part tutorial, I will explain how to develop your own template engine that uses a simple find and replace technique. In part 1, you will learn how to find and replace special tags known as placeholders with scalar values and in part 2, I will explain how to use simple objects as placeholders.

Part 1

Find and replace template engines have existed for a while and work well for some situations where a full stack template engine is not required. Consider a simple scenario of an email template, which only requires populating placeholder tags with dynamic data. In these situations, a light weight find and replace template engine can be sufficient.

Consider the following email template markup.

  1. <div>   
  2.     <h1>Hi {@first_name},</h1>   
  3.     <p>{@message}</p>   
  4.     <p>   
  5.         Kind regards,<br/>   
  6.         {@sender_name}   
  7.     </p>   
  8. </div>  
The markup in the code sample above contains three placeholders. The syntax for placeholders is {@placeholder name}. You can define your own syntax for placeholders but it should be unique so that similar words that are not placeholders don't get replaced. With the use of the str_replace() function, each placeholder can be replaced with a scalar value. The code below demonstrates this by replacing each placeholder with a static scalar value.

  1.     $template = file_get_contents('template.txt');   
  2.        
  3.     $template = str_replace( "{@first_name}",  "John", $template);    
  4.     $template = str_replace( "{@message}",  "Welcome to our new mailing list.", $template);    
  5.     $template = str_replace( "{@sender_name}",  "Syed", $template);    
  6.     echo $template;  
The code above will produce the expected results, however it is not dynamic. For every new placeholder a new replace statement must be added. The code becomes ugly to maintain as well as ugly to look at.

To make the code more dynamic, the data can be stored in an array with the placeholder name as the array key. We can then iterate through the array and use the array key/value to replace placeholders as demonstrated in the following code.

  1.     $params = array(   
  2.          "first_name" =>  "John",   
  3.          "message" =>  "Welcome to our new mailing list.",   
  4.          "sender_name" =>  "Syed"   
  5.     );   
  6.        
  7.     $template = file_get_contents( "template.txt");   
  8.        
  9.     foreach($params as $key=>$value){   
  10.         $template = str_replace( "{@$key}", $value, $template);   
  11.     }   
  12.     echo $template;  
This approach makes the code more dynamic in finding and replacing placeholders. We can wrap the code in a class to make the code reusable and provide methods to load a template and assign placeholder values. The final code sample below shows a simple Template class with usage.

  1. <?php   
  2.   
  3.     class Template {   
  4.            
  5.         private $template;   
  6.         private $parameters = array();   
  7.            
  8.         public function __construct($file = null){   
  9.             if($file){   
  10.                 $this->load($file);   
  11.             }   
  12.         }   
  13.            
  14.         public function load($file){   
  15.             if(file_exists($file)){   
  16.                 $this->template = file_get_contents($file);   
  17.             }   
  18.         }   
  19.            
  20.         public function addParameter($key, $value){   
  21.             if(is_scalar($value)){   
  22.                 $this->parameters[$key] = $value;   
  23.             }   
  24.         }   
  25.            
  26.         public function render(){   
  27.             foreach($this->parameters as $key=>$value){   
  28.                 $this->template = str_replace( "{@" . $key .  "}", $value, $this->template);    
  29.             }   
  30.             return $this->template;   
  31.         }   
  32.     }   
  33.        
  34.     // Usage.   
  35.        
  36.     // Load the template file.   
  37.     $emailTemplate = new Template( "template.txt");   
  38.        
  39.     // Assign placeholder variable.   
  40.     $emailTemplate->addParameter( "first_name",  "John");   
  41.     $emailTemplate->addParameter( "message",  "Welcome to our new mailing list.");   
  42.     $emailTemplate->addParameter( "sender_name",  "Syed");   
  43.        
  44.     // Render the template   
  45.     echo $emailTemplate->render();   
  46.        
  47. ?>  
By now you would have realized that, this approach can only replace placeholders with scalar values. In PHP - Simple Template Engine Part 2, I will explain how to use objects in templates which will require the use of regular expressions.

No comments:

Post a Comment