Friday, November 2, 2007

PHP Tags are Ugly

(Or, "Why Are There So Many PHP Templating Engines?")

Remember when most PHP scripts used short tags?
<? $users = get_users(); ?>
Along with the short syntax came the quick and easy output syntax:
<?= $user['name'] ?>
Then, after XHTML hit the scene, the short tag syntax conflicted with the XML processing directive syntax. So the PHP coding standards changed to long tag syntax. This adds 3 characters to every tag:
<?php echo $user['name'] ?>
The tag syntax is not only longer, it forces the developer to use an 'echo' call when before, an equals sign was sufficient. This adds another 5 characters to tags that output something.

The long-tag syntax helped spawn a myriad of templating languages, which many developers consider silly, since PHP already is a templating language.

If you want your templates to be secure and logically correct, you have to escape those characters that HTML considers 'special':
<?php echo htmlspecialchars($user['name']) ?>
Consider the same statement in RHTML (a popular templating system for Ruby):
<%=h user['name'] %>
The RHTML version is vastly simpler.

With that kind of syntax, there's little incentive to use or create a separate templating language.