10 lines implementation of PHP template engine

PHP provides the following functions.

  • extract($array) — import associated array as local variables.
  • include($filename) — read PHP file and evalue it.

Using these functions, you can get your own PHP template engine in 10 lines. The following is an example.

<?php  /* MyTemplateEngine.php */
$TEMPLATE_DIR = NULL;
function include_template($_filename, $_context) {
    global $TEMPLATE_DIR;
    extract($_context);
    if (! file_exists($_filename) && $TEMPLATE_DIR)
        $_filename = "$TEMPLATE_DIR/$_filename";
    include($_filename);
}
?>

If you want include_template() to return string, you can use ob_start() and ob_get_clean() for buffering.

<?php  /* MyTemplateEngine.php */
$TEMPLATE_DIR = NULL;
function include_template($_filename, $_context) {
    global $TEMPLATE_DIR;
    extract($_context);
    if (! file_exists($_filename) && $TEMPLATE_DIR)
        $_filename = "$TEMPLATE_DIR/$_filename";
    ob_start();
    include($_filename);
    return ob_get_clean();
}
?>

If you want layout template feature, the following example will help you.

<?php  /* MyTemplateEngine.php */
$LAYOUT_TEMPLATE = NULL;
function render_template($_filename, $_context, $_layout=NULL) {
    global $LAYOUT_TEMPLATE;
    $s = include_template($_filename, $_context);
    if (@$_context['_layout'] !== NULL)
        $_layout = $_context['_layout'];
    elseif ($_layout === NULL)
        $_layout = $LAYOUT_TEMPLATE;
    if ($_layout) {
        $_context['_content'] = $s;
        $s = include_template($_layout, $_context);
    }
    return $s;
}

$TEMPLATE_DIR = NULL;
function include_template($_filename, &$_context) {
    global $TEMPLATE_DIR;
    extract($_context);
    if (! file_exists($_filename) && $TEMPLATE_DIR)
        $_filename = "$TEMPLATE_DIR/$_filename";
    ob_start();
    include($_filename);
    return ob_get_clean();
}
?>

There are thee way to specify layout template.

  • Set layout template file name to global variable $LAYOUT_TEMPLATE
  • Pass layout template file name to render_template() as third argument
  • Assign layout template file name to $_context['_layout'] in template file

If you set FALSE to layout template file name then layout template will not used.

The following is an example of layout template.

templates/layout.php:

<html>
  <body>
    <h1><?php echo $title; ?></h1>
<?php echo $_content; ?>
  </body>
</html>

templates/template.php:

<ul>
<?php foreach ($list as $item): ?>
  <li><?php echo $item; ?></li>
<?php endforeach; ?>
</ul>

example.php:

<?php
require_once('MyTemplateEngine.php');
$TEMPLATE_DIR = 'templates';
$LAYOUT_TEMPLATE = 'layout.php';
$context = array('title'=>'Example', 'list'=>array('AAA','BBB','CCC'));
echo render_template('template.php', $context);
?>

result:

<html>
  <body>
    <h1>Example</h1>
<ul>
  <li>AAA</li>
  <li>BBB</li>
  <li>CCC</li>
</ul>
  </body>
</html>

See:

Leave a reply