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.
- <div>
- <h1>Hi {@first_name},</h1>
- <p>{@message}</p>
- <p>
- Kind regards,<br/>
- {@sender_name}
- </p>
- </div>
- $template = file_get_contents('template.txt');
- $template = str_replace( "{@first_name}", "John", $template);
- $template = str_replace( "{@message}", "Welcome to our new mailing list.", $template);
- $template = str_replace( "{@sender_name}", "Syed", $template);
- echo $template;
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.
- $params = array(
- "first_name" => "John",
- "message" => "Welcome to our new mailing list.",
- "sender_name" => "Syed"
- );
- $template = file_get_contents( "template.txt");
- foreach($params as $key=>$value){
- $template = str_replace( "{@$key}", $value, $template);
- }
- echo $template;
- <?php
- class Template {
- private $template;
- private $parameters = array();
- public function __construct($file = null){
- if($file){
- $this->load($file);
- }
- }
- public function load($file){
- if(file_exists($file)){
- $this->template = file_get_contents($file);
- }
- }
- public function addParameter($key, $value){
- if(is_scalar($value)){
- $this->parameters[$key] = $value;
- }
- }
- public function render(){
- foreach($this->parameters as $key=>$value){
- $this->template = str_replace( "{@" . $key . "}", $value, $this->template);
- }
- return $this->template;
- }
- }
- // Usage.
- // Load the template file.
- $emailTemplate = new Template( "template.txt");
- // Assign placeholder variable.
- $emailTemplate->addParameter( "first_name", "John");
- $emailTemplate->addParameter( "message", "Welcome to our new mailing list.");
- $emailTemplate->addParameter( "sender_name", "Syed");
- // Render the template
- echo $emailTemplate->render();
- ?>
No comments:
Post a Comment