Loops in templates using PHP
22 March 2007I've been an advocate of seperating logic from presentation for a long time now. But after working on a few large PHP projects lately, I've decided that I need to have loops in my template class, it's too time conusming creating seperate templates to be placed inside loops.
I started off by defining a readable syntax for the loops inside my templates.
<@loop(contacts)
{
<p>Name: Aaron Saray<br />
Sex: {sex}</p>
}
@>'contacts' would be the name of the array I'm going to loop through.
Here is the function that will process the loop. Simply pass a string containing the loop, and it will return the output.
<?php
function parseLoop($loop)
{
$loop_result = '';
// get the name of the loop
preg_match('/loop((.*))/', $loop, $loop_name);
// get the loop contents
preg_match('/{(.*)}/s', $loop, $loop_contents);
// get all the vars from loop_contents
preg_match_all('/{(.*)}/', $loop_contents[1], $vars);
// loop through the global array
foreach($arrays[$loop_name[1]] as $item)
{
$loop_item = $loop_contents[1];
// loop through every variable found, and replace it with its value in the global array
foreach($vars[1] as $var)
{
$loop_item = @str_replace('{'.$var.'}', $item[$var], $loop_item);
}
$loop_result .= $loop_item;
}
return $loop_result;
}
?>
And here is the array containing the contacts.
<?php
$arrays = array('contacts' = array(
array('name' => 'jane', 'sex' => 'f'),
array('name' => 'bob', 'sex' => 'm')
);
?>
To use the function you need to find the loops in the templates using regular expressions, pass it through parseLoop(), then replace the loop block with the output.
Gavin Benda
Awesome work Rich, I need to get this into my templating system!