Friday, June 04, 2010

The PHP Template Pattern -- PHP As Its Own Templating Language

A while back, I read PHP Templates: Smarter Sans Smarty, and was immediately impressed. The article makes the case that rather than using a separate template language (like Smarty), one should use PHP itself.

Or, put another way - don't use a Domain Specific Language, when the language itself will do the trick.

Even cooler than the argument put forth , is the code provided to make this functionality painless to use. The core apply_template function is so elegant, in fact, it deserves to be repeated here:

/**
 * 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;
}

Since reading this article, I've used the above templating patterning in a variety of scenarios, and I'm consistently impressed with how well it works. I love that the HTML templates give me access to not only simple variable substitution, but also the full power of PHP, such as conditionals and calling additional functions. I especially like how cleanly templates can nest within each other. All it takes is a call to apply_template from within another template. Templates even managed to leverage local variables well.

I just love pithy solutions like this one.

3 comments:

  1. Anonymous11:55 AM

    It sounds like you're just using a bad templating system. Something like Template-Toolkit (perl, http://search.cpan.org/~abw/Template-Toolkit-2.22/).

    It has variables (substitution and assignment), loops, conditionals, blocks (essentially subroutines), flow control, macros, the ability to bind arbitrary code/plugins into the namespace from the Perl side, and, if you enable it, drop back into Perl.

    I can't imagine being happy with a templating missing most of those.

    ReplyDelete
  2. Jon -

    The point isn't that Smarty or other templating systems are missing those features -- it's just that core PHP already offers them.

    Why add layers of complexity to your code, so you can reference a variable like:

    {foo}
    instead of


    Especially, when by giving up a little syntax, you gain an entire language - instead of sub-language built on top of your core language.

    ReplyDelete
  3. Thank you. This solves all my template problems.

    ReplyDelete