PHP as a template language
Thursday, February 11th, 2010
It's been a while since I blogged, but I just ran into another zealot pointing me to NoSmarty.net when I mentioned templating.
I think I've said it before. The tool you use should depend on the job you're trying to do. So to say that Smarty is wrong just because it is, does not feel right.
I agree that in many cases PHP can be used as a template language just fine, but there are situations where a Smarty template (or any other templating engine) is just that more pleasant.
Here's a bit of template code that I encountered yesterday. Its use of php as a template language is hideous. Because it's a template for an xml message and because it needs to cope with systems with short open tags on and off, it looks like this:
<?php echo '<'; ?>?xml version="1.0" encoding="UTF-8"?> <result processed="<?php echo $data["processed"]?"yes":"no"; ?>" <?php if (isset($data["orderid"])) { ?>orderId="<?php echo $data["orderid"]; ?>"<?php } ?> > <?php if (isset($data["error"])) { ?><error message="<?php echo $data["error"]; ?>" /><?php } ?> </result>
Hideous!
Here's what it would look like in Smarty:
<?xml version="1.0" encoding="UTF-8"?> <result processed="{if $data.processed}yes{else}no{/if}" {if $data.orderid} orderId="{$data.orderid}"{/if}> {if $data.error} <error message="{$data.error}" />{/if} </result>
Yes, the first one is slightly more efficient, but the second one is actually readable for the average person.
Anybody claiming that <?php } ?> is 'just as convenient' as {/if} does not think clearly.
In my humble opinion, of course.


Long time no blog