Monday, November 21, 2011

Minimum Template Engine in PHP

Here is an example code for describing the Output Control functions in PHP.

<?php

require_once 'classes/Renderer.php';

$renderer = new Renderer();

$renderer->template = '/path/to/templates/index.php';
$renderer->params = array(
    'name' => 'Blogger',
    'url' => 'http://www.blogger.com/',
);

echo $renderer->render();

classes/Renderer.php:

<?php

class Renderer
{
    var $template;
    var $params = array();

    function render()
    {
        ob_start();
        include $this->template;
        $output = ob_get_contents();
        ob_clean();

        return $output;
    }
}

/path/to/templates/index.php:

<dl>
  <dt>Name</dt>
  <dd><?php echo htmlspecialchars($this->params['name']); ?>
  </dd>
  <dt>URL</dt>
  <dd><?php echo htmlspecialchars($this->params['url']); ?></dd>
</dl>

It may become easier to understand if you "echo", rather than "include", the contents of /path/to/templates/index inside the Renderer->render method.