[nycphp-talk] Templating engines
paul at devonianfarm.com
paul at devonianfarm.com
Thu Jan 17 15:30:23 EST 2008
I've been all over the map. Years ago I was against templating systems, then I was a big fan of smarty, now my templating strategy is the one that's used in symfony: don't use a separate templating system, but impose some discipline on the way you use PHP.
My answer would be different in languages that aren't as facile as PHP... I would use a templating system in Perl, Java or Ruby, but in a systems PHP, ColdFusion or ASP.NET, which were designed from the beginning to build web apps, it's hard to develop a templating system which is better than the one the language gives you.
Study the "view" part of the symfony docs if you want to get a good picture of how do this, but you don't need a heavyweight framework to get the benefits... I built an MVC "microframework" in 80 lines of PHP and wrote another 120 lines worth of helper functions that dealt with common annoyances such as populating <select> lists. The big concepts are:
* layouts: you need some mechanism for selecting a "master template" that your page appears in. This looks like
<html>
<head>...<title><?php q($title) ?></title>...
</head>
<body>
... header stuff ...
<?php echo $real_content ?>
... footer stuff ...
</body>
</html>
Note that the master template is real HTML (<?php is a processing instruction) so you (or a designer) can edit it in dreamweaver or your favorite tools.
* partials: a partial is a PHP file that emits HTML that goes into slots like the $real_content slot... With output buffering (see the ob_start function) you can capture the output of a PHP "template" and put it in a string for further processing. With some work you can do this recursively, so partials end up inside partials.
* helpers: these are functions that help you write views. For instance, the q() function above is
function q($string) {
echo(htmlspecialchars($q));
}
You'll need helpers to make form elements for you, for instance, something like
draw_select_list($name,$options,$selected)
where the $options are an associative array of values and display text.
Symfony has a mature view system that has caching and other advanced features (I wish I could say it was as mature in the data access department)
For my day job I'm working on an ASP.NET microframework that uses the same ideas.
----
Paul Houle
http://animalphotos.info/a/
More information about the talk
mailing list