Page 1 of 1
Templating using while() loops
Posted: Fri May 25, 2007 5:06 pm
by s.dot
Code: Select all
<?php
$description = 'My Blog';
require 'header.php';
//get the 10 latest blogs
$blogr = mysql_query("SELECT * FROM `blogs` ORDER BY `id` DESC LIMIT 10") or die(mysql_error());
while($blog_a = mysql_fetch_assoc($blogr))
{
$tpl->assign('blog_title', $blog_a['title']);
$tpl->assign('blog_music', $blog_a['music']);
$tpl->assign('blog_mood', $blog_a['mood']);
$tpl->assign('blog_time', date("n-d-Y \a\\t g:i A", $blog_a['time']));
$tpl->assign('blog_entry', $blog_a['entry']);
}
$tpl->display('blog.tpl');
require 'footer.php';
?>
I'm having trouble figuring out how to assign the variables from the $blog_a array into the template (template lite). By doing it like I am above, it will only list one blog on the page. I want to show 10.
The only thing I can think of would be assigning $blog_a to a container array inside of the loop and pass that container array to the template, and then loop over it in the template. That seems a bit... far fetched. Am I missing something extremely obvious?
Posted: Fri May 25, 2007 5:22 pm
by Luke
Assign it to an array and then loop through it in the template. There's nothing far-fetched about that at all.
Posted: Fri May 25, 2007 5:49 pm
by s.dot
Okay, so I've got this:
blog.php
Code: Select all
<?php
$description = 'My Blog';
require 'header.php';
require 'includes/php/functions.php';
//get the 10 latest blogs
$blogr = mysql_query("SELECT * FROM `blogs` ORDER BY `id` DESC LIMIT 10") or die(mysql_error());
$blogs = array();
while($blog_a = mysql_fetch_assoc($blogr))
{
$blogs[] = array_merge($blog_a, array('url' => make_safe_url($blog_a['title'])));
}
$tpl->assign('blogs', $blogs);
$tpl->display('blog.tpl');
require 'footer.php';
?>
blog.tpl
Code: Select all
<div class="mainleft">
<h1>My Blog, My World</h1>
{ foreach value=value from=$blogs }
<h2>{ $value.title }</h2>
<p class="blogtime">{ $value.time|date:"l, F dS, Y" }</p>
{ $value.entry|truncate:250:" ..." } [<a href="{ $value.id }/{ $value.url }">read more</a>]
{ /foreach }
</div>
Seems a bit odd at first, but I suppose anything out of the ordinary from what I've been doing will seem odd. Hopefully this is the most practical way of doing it. Seems like it'd use more resources by assigning to an extra array, though.
Posted: Fri May 25, 2007 5:55 pm
by John Cartwright
If we were all worried about a couple extra cycles here and there, we wouldn't be using PHP

Posted: Fri May 25, 2007 6:56 pm
by RobertGonzalez
You got it spot on. You could also use the section tag (it is similar to a for loop). Good job.