Rigidly defined areas of doubt and uncertainty.

Sunday, December 09, 2007

The simplest template engine that could possibly work

In Templates Are Code, Too Hendrik explains in detail why the last thing the world needs is another template engine. So here's mine.

function template($template, $data) {
extract($data);
ob_start();
include $template;
return ob_get_clean();
}

That's all you need to write a template engine in PHP, because PHP is a template engine. You write your templates like this:


<html>
<head>
<title><?=$title?></title>
</head>
<body>
<h1><?=$title?></h1>
</body>
</html>



And call them like this:

<?php
echo template("template.tpl", array("title" => "Hello, world!"));
?>


And you can combine them like this:

<?php
$content = template("content.tpl",
array("heading" => "Content heading",
"body" => "content body"));
echo template("container.tpl",
array("title" => "Hello, world!",
"content" => $content));
?>