Separating PHP from HTML can give cleaner code. There are a few templating engines that do this for you. However, if you want something simple yourself, then here goes.
Say you want to show a list of books. Here's how a template could work. First we write the template and call it book.inc :
book.inc
<tr>
<td> < ?php echo $title? > </td>
<td> < ?php echo $author? > </td>
<td> < ?php echo $pulisher? > </td>
</tr>
Next we include book.inc into our code in books.php :
books.php
<?php
<table>
foreach ($books as $book) {
$title = $book->title;
$author = $book->author;
$publisher = $book->publisher;
include ('book.inc')
}
</table>
?>
This way, book.inc acts as a template and is substituted with the value of each book.
November 8, 2007
Subscribe to:
Posts (Atom)