Simple news archive with Smarty?
There is a simple table of news articles: [ id | title | body | 开发者_如何转开发created ]
.
What is the best way to create a simple news archive using smarty from a full collection of articles ordered by created date?
In the format:
- 2009
- 12.11. Title
- 03.03. Title
- 01.01. Title
- 2008
- 11.12. Title
- 04.03. Title
- 02.03. Title
- 16.02. Title
- 2007
- ...
- ...
<ul>
{foreach item=p from=$news}
<li>{$p->created} {$p->title}</li>
{/foreach}
</ul>
There are 2 ways
- You create the structure in Smarty
- You group results from db by year
The first would go
$rows = $db->query('select year, title from news');
$smarty->assign('news', $rows);
// smarty code
{if count($rows) > 0}
{assign var=lastYear value=0}
<ul><li>
{foreach name=foo from=$rows item=item}
{if $smarty.foreach.foo.first}
{$row.year}<ul>
{elseif $lastYear != $row.year}
</ul></li><li>{$row.year}<ul>
{/if}
{assign var=lastYear value=$row.year}
<li>{$row.title}</li>
{/foreach}
</ul></li></ul>
{/if}
The other one is to group the values in php:
$rows = $db->query('select year, title from news');
$news = array();
foreach($rows as $row) {
$news[$row['year']][] = $row['title'];
}
$smarty->assign('news', $news);
// smarty code
<ul>
{foreach from=news key=year item=rows}
<li>{$year}<ul>
{foreach from=$rows item=row}
<li>{$row}</li>
{/foreach}
</ul></li>
{/foreach}
</ul>
The choice is up to you
精彩评论