I'm still figuring out what the best way to keep php and layout separate is not too much fluff. At the moment, I really like the inclusion template approach, because it is so simple and has no restrictions.
So, for your example, you will have a php file (example.php) that looks like this:
<?php $custTrans = Customer.getTransactions(); $displ_transactions = array(); foreach ($custTrans as $ct){ $transaction = array( 'amount' => $ct[0], 'date' => $ct[1]; 'product' => $ct[2]; ); $displ_transactions[] = $transaction;
And then you need the second file (example.tpl.php):
<?php foreach ($displ_transactions as $transaction) { ?> <div class="custTrans"> <span class='custTransAmount'><?php echo $transaction['amount'] ?></span>; <span class='custTransDate'><?php echo $transaction['date'] ?></span>; <span class='custTransproduct'><?php echo $transaction['product'] ?></span>; </div> <?php } ?>
Just call example.php in your browser and you will see the same result as before. This is good and good for small sites because this method causes some overhead. If you are serious about templates, use smarty. it is easy to learn and it has automatic caching, so it is very fast.
I just understand that you can also do this as follows:
example.php:
<?php $custTrans = Customer.getTransactions(); foreach ($custTrans as $ct){ $amount = $ct[0]; $date = $ct[1]; $product = $ct[2]; include 'example.tpl.php'; } ?>
example.tpl.php:
<div class="custTrans"> <span class='custTransAmount'><?php echo $amount ?></span>; <span class='custTransDate'><?php echo $date ?></span>; <span class='custTransproduct'><?php echo $product ?></span>; </div>
Use whatever suits you :)
source share