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) {
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:


And call them like this:

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

And you can combine them like this:

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