For the past 4 or 5 years I’ve been a proponent of using PHP as it’s own template engine. I cringe every time I see someone using smarty, btemplate, fastTemplate, etc… because I’ve never had to do anything in my html that couldn’t be done with PHP. Never! Why add a layer to your app if you don’t have to?
To illustrate this I’m going to show you a template written in a template engine, and then in PHP.
Here’s an example from the Smarty website
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| <table border="0" width="300">
<tr>
<th colspan="2" bgcolor="#d1d1d1">Guestbook Entries (<a href="{$SCRIPT_NAME}?action=add">add</a>)</th>
</tr>
{foreach from=$data item="entry"}
<tr bgcolor="{cycle values="#dedede,#eeeeee" advance=false}">
<td>{$entry.Name|escape}</td>
<td align="right">{$entry.EntryDate|date_format:"%e %b, %Y %H:%M:%S"}</td>
</tr>
<tr>
<td colspan="2" bgcolor="{cycle values="#dedede,#eeeeee"}">{$entry.Comment|escape}</td>
</tr>
{foreachelse}
<tr>
<td colspan="2">No records</td>
</tr>
{/foreach}
</table> |
Here’s an example using PHP. e() is an escaping function you write yourself.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| <table border="0" width="300">
<tr>
<th colspan="2" bgcolor="#d1d1d1">Guestbook Entries (<a href="{$SCRIPT_NAME}?action=add">add</a>)</th>
</tr>
<?php if ( count( $data ) ): ?>
<?php foreach( $data as $entry ): ?>
<tr bgcolor="<?php if( $i++ % 2 ): ?>#dedede<?php else: ?>#eeeeee<?php endif; ?>">
<td><?= e( $entry['name'] ) ?></td>
<td align="right"><?= date( $entry['entryDate'], 'e b Y H M S' ) ?></td>
</tr>
<tr>
<td colspan="2" bgcolor="<?php if( $i % 2 ): ?>#dedede<?php else: ?>#eeeeee<?php endif; ?>"><?= e( $entry['comment'] ) ?></td>
</tr>
<?php endforeach; ?>
<?php else: ?>
<tr>
<td colspan="2">No records</td>
</tr>
<?php endif; ?>
</table> |
As you can see there is only 2 added lines of code. I had to add an if statement to account for smarty’s foreachelse. No added layer. No extra work for the interpreter. Just as readable (unless you’re a PHP developer, then it will be more readable)
In closing read this post on the sitepoint forums. Pay particular attention to Voostind’s replies (#1, #2, #3)