smarty foreach 最全用法

<?php
$search_condition 
"where name like '$foo%' ";
$sql 'select contact_id, name, nick from contacts '.$search_condition.' order by name';
$smarty->assign('results'$db->getAssoc($sql) );
?>

The template which display "None found" if no results with {foreachelse}.php

藉助{foreachelse}標記在沒有結果時模板輸出"None found"字樣。sql

{foreach key=cid item=con from=$results}     數組

 <a href="contact.php?contact_id={$cid}"> ide

{$con.name} - {$con.nick}</a><br /> oop

{foreachelse}      this

No items were found in the search  spa

{/foreach} 索引

.index

index contains the current array index, starting with zero.ci

.index包含當前數組索引,從零開始。rem

Example 7-10. index example

例 7-10. index示例

{* The header block is output every five rows *}
{* 每五行輸出一次頭部區塊 *}
<table>
{foreach from=$items key=myId item=i name=foo}
{if $smarty.foreach.foo.index % 5 == 0}
<tr><th>Title</th></tr>
{/if}
<tr><td>{$i.label}</td></tr>
{/foreach}
</table>
.iteration

iteration contains the current loop iteration and always starts at one, unlike index. It is incremented by one on each iteration.

iteration包含當前循環次數,與index不一樣,從1開始,每次循環增加1。

Example 7-11. iteration and index example

例 7-11. iteration和index示例

{* this will output 0|1, 1|2, 2|3, ... etc *}
{* 該例將輸出0|1, 1|2, 2|3, ... 等等 *}
{foreach from=$myArray item=i name=foo}
{$smarty.foreach.foo.index}|{$smarty.foreach.foo.iteration},
{/foreach}
.first

first is TRUE if the current {foreach} iteration is the initial one.

first在當前{foreach}循環處於初始位置時值爲TRUE。

Example 7-12. first property example

例 7-12. first屬性示例

{* show LATEST on the first item, otherwise the id *}
{* 對於第一個條目顯示LATEST而不是id *}
<table>
{foreach from=$items key=myId item=i name=foo}
<tr>
<td>{if $smarty.foreach.foo.first}LATEST{else}{$myId}{/if}</td>
<td>{$i.label}</td>
</tr>
{/foreach}
</table>
.last

last is set to TRUE if the current {foreach} iteration is the final one.

last在當前{foreach}循環處於最終位置是值爲TRUE。

Example 7-13. last property example

例 7-13. last屬性示例

{* Add horizontal rule at end of list *}
{* 在列表結束時增長一個水平標記 *})
{foreach from=$items key=part_id item=prod name=products}
<a href="#{$part_id}">{$prod}</a>{if $smarty.foreach.products.last}<hr>{else},{/if}
{foreachelse}
... content ...
{/foreach}
.show

show is used as a parameter to {foreach}. show is a boolean value. If FALSE, the {foreach}will not be displayed. If there is a {foreachelse} present, that will be alternately displayed.

show是{foreach}的參數. show是一個布爾值。若是值爲FALSE,{foreach}將不被顯示。若是有對應的{foreachelse},將被顯示。

.total

total contains the number of iterations that this {foreach} will loop. This can be used inside or after the {foreach}.

total包括{foreach}將循環的次數,既能夠在{foreach}中使用,也能夠在以後使用。

Example 7-14. total property example

例 7-14. total屬性示例

{* show rows returned at end *}{* 在結束位置顯示行數 *}{foreach from=$items key=part_id item=prod name=foo}{$prod.name><hr/>{if $smarty.foreach.foo.last}<div id="total">{$smarty.foreach.foo.total} items</div>{/if}{foreachelse}... something else ...{/foreach}
相關文章
相關標籤/搜索