Pure PHP template function

On another page, I promoted the use of pure PHP templates in favor of templating systems such as Smarty. Using pure PHP templates and still achieving separation of business and presentation logic can be as simple as require()ing your template from your controller function.

But, sometimes you might want a little encapsulation. Before you start writing your own My1337TemplateEngine class full of uselessfull methods such set_variable() and unset_variable(), I suggest you take a look at the following function: (Indeed, that's a function, not a class.)

Presenting … the pure PHP template processor!

<?php
 
/**
 * Execute a PHP template file and return the result as a string.
 */
function apply_template($tpl_file, $vars = array(), $include_globals = true)
{
  extract($vars);
 
  if ($include_globals) extract($GLOBALS, EXTR_SKIP);
 
  ob_start();
 
  require($tpl_file);
 
  $applied_template = ob_get_contents();
  ob_end_clean();
 
  return $applied_template;
}
 
?>

What more do you actually need when working with templates? You've got your array of template variables there, and, for the lazy amongst us, the option to simply pull all the globals into the template's scope.

Relatedly…

You might want to learn why I think that, when using PHP, it doesn't make any sense to use anything but PHP for your templates: PHP Templates: Smarter sans Smarty.