Last night I coded the main page for http://www.fexboards.com, and before that I coded the tutorial database for that same site (organized very similar to this sites hack section, although I believe coded quite differently). I knew I was going to have to deal with a lot of repeating-element templates. By repeating-element templates, I mean templates such as the infamous postbit template, something which when its finally used, will be echoed out many times in a row in accordance with the results of a database query. The function I wrote has you supply a comma separated list of variables as they would appear in the database query, your master template name, your subtemplate name, the table(s) present in the from clause of the query, and the conditions under which the selection will take place (the where clause, you can also include order by and group by stuff here).
An example of its use is as follows:
PHP Code:
$mainpage[top10posters] = loop_template('userid,username,posts',
'mainpage','top10posters','user',
'order by posts desc limit 10');
That one function call right there will store all the iterations of the mainpage_top10posters template, filled with the top 10 posters' information, into $mainpage[top10posters]. That means after you run this you can just include your final template that just echoes out $mainpage[top10posters] where its needed.
The main limitation is that you cannot do any processing on the variables. If you wanted to loop through posts and you wanted to parse the pagetext with bbcodeparse(), you would have to hack up the function or just forget about using it. Nonetheless, I have found it pretty useful.
Comments/criticism/suggestions appreciated. The function is attached.
I just realized this would probably do better in the Hacking Hints and Tips forum. If some bored mod feels like moving it for me it would be appreciated
Umm, this could be written a lot shorter and faster...
PHP Code:
function loop_template($vars, $template, $subtemplate, $table, $conditions = '') {
global $DB_site;
$dblink = $DB_site->query("SELECT $vars FROM $table$conditions");
while ($db_array = $DB_site->fetch_array($dblink)) {
foreach ($db_array as $field => $value) { // DO NOT use while here
$array["{$subtemplate}_{$field}"] = $value;
unset($array["$field"]);
}
eval('$return .= "'.gettemplate($template.'_'.$subtemplate).'";');
}
$DB_site->free_result($dblink);
return $return;
}
Thanks a lot, firefly. I feel really dumb about not realizing that I could have gotten fieldnames from the mysql_fetch_array() results. I haven't gotten used to the functions in vb quite yet, so I can almost justify my unneeded usage of output buffering. And nice call on defaulting the last argument to ''.
I still think this function is pretty useful, but use firefly's revised version, does the same thing but with less code and less load