How to print a recordset using Smarty?
I need to开发者_Go百科 show the result of a query(mysql), how can I loop the recordset without assign the values to an array? Now I do:
while($row = $this->mysql->fetch($rs)){
val[] = $row
}
$this->smarty->assign('val', val);
then (in the template.tpl)
{section name=nr loop=$val}
{$val[nr].cod}<br />
{sectionelse}
<h1>No record</h1>
{/section}
How can I optimize it?
You can use Smarty's foreach, although it doesn't make it any shorter:
{if $val}
{foreach from=$val item=nr}
{$nr.cod}<br />
{/foreach}
{else}
<h1>No record</h1>
{/if}
maybe {html_table} can help. Otherwise you're free to iterate your rows and cols however you like:
{foreach $val as $row}
{if $row@first}
<table>
<tbody>
{/if}
{foreach $row as $cell}
{if $cell@first}
<tr>
{/if}
<td>{$cell|escape:"html}</td>
{if $cell@last}
</tr>
{/if}
{foreach}
{if $row@last}
</tbody>
</table>
{/if}
{foreachelse}
<p>No Data</p>
{/foreach}
(Smarty3 syntax of {foreach})
You can also output the cells' keys:
{foreach $val as $row}
{if $row@first}
<table>
<thead>
<tr>
{foreach $row as $cell}
<th>{$cell@key|escape:"html}</th>
{/foreach}
</tr>
</thead>
<tbody>
{/if}
{foreach $row as $cell}
{if $cell@first}
<tr>
{/if}
<td>{$cell|escape:"html}</td>
{if $cell@last}
</tr>
{/if}
{foreach}
{if $row@last}
</tbody>
</table>
{/if}
{foreachelse}
<p>No Data</p>
{/foreach}
精彩评论