Template system in PHP

This template system will simply find certain strings in the HTML template and replace this with dynamic content.

class template
{
   var $template;
   var $data = array();

We will firstly define a class with two fields, one to store the template and the other to store the data to swap dynamically.

function template($file)
{
   $this->template = $this->file_load($file);
}

The constructor will load the template from the file specified. This will be the main template that the data will be loaded into.

function file_load($file)
{
   if(file_exists($file))
      return file_get_contents($file);
   else
      die('File "'.$file.'" cannot be loaded.');
}

The function loads the file if it exists otherwise it will return an error message.

function addData($key, $value)
{
   $this->data[$key] = $value;
}

function addFileData($key, $file)
{
   $this->addData($key, $this->file_load($file));
}

To add data a key must be specified that will be the string that will be replaced within the template, and the associated data as the second argument. The second function takes a key as the first argument and a file as the second. The file will be loaded and will be replaced in the main template.

function make_template()
{
   foreach ($this->data as $key => $value)
      $this->template = str_replace('['.$key.']', $value, $this->template);
   echo $this->template;
}

Finally a method to merge the data into the document and print the template.

To use this class first create a new object with the main template file and start to load the dynamic data.

$temp = new template('default_template.html');
$temp->addData('TITLE', 'title');
$temp->addData('SUBJECT', date('dmy'));
$temp->addData('NEWS', 'news');
$temp->make_template();

This example loads a simple news template and loads three data items, a title, subject and the news.

Downloads

Categories

Tags

No tags

Social