smarty foreach详解

2016年4月24日 由 Creater 留言 »

{foreach} is used to loop over an associative array as well a numerically-indexed array, unlike {section} which is for looping over numerically-indexed arrays only. The syntax for {foreach} is much easier than {section}, but as a tradeoff it can only be used for a single array. Every{foreach} tag must be paired with a closing {/foreach} tag.

{foreach} 用于像循环访问一个数字索引数组一样循环访问一个关联数组,与仅能访问数字索引数组的{section}不同,{foreach}的语法比 {section}的语法简单得多,但是作为一个折衷方案也仅能用于单个数组。每个{foreach}标记必须与关闭标记{/foreach}成对出现。

Attribute Name属性名称 Type类型 Required必要 Default默认值 Description描述
from array数组 Yes必要 n/a The array you are looping through
item string字符串 Yes必要 n/a The name of the variable that is the current element
key string字符串 No可选 n/a The name of the variable that is the current key
name string字符 No可选 n/a The name of the foreach loop for accessing foreach properties
  • Required attributes are from and item.
  • from和item是必要属性
  • The name of the {foreach} loop can be anything you like, made up of letters, numbers and underscores, like PHP variables.
  • {foreach}循环的name可以是任何字母,数组,下划线的组合,参考PHP变量。
  • {foreach} loops can be nested, and the nested {foreach} names must be unique from each other.
  • {foreach}循环可以嵌套,嵌套的{foreach}的名称应当互不相同。
  • The from attribute, usually an array of values, determines the number of times {foreach} will loop.
  • from属性通常是值数组,被用于判断{foreach}的循环次数。
  • {foreachelse} is executed when there are no values in the from variable.
  • 在from变量中没有值时,将执行{foreachelse}。
  • {foreach} loops also have their own variables that handle properties. These are accessed with: {$} with “name” being the name attribute.
  • {foreach}循环也有自身属性的变量,可以通过{$}访问,其中”name”是name属性。

    Note: The name attribute is only required when you want to access a {foreach} property, unlike {section}. Accessing a {foreach} property with name undefined does not throw an error, but leads to unpredictable results instead.

  •   注意:name属性仅在需要访问{foreach}属性时有效,与{section}不同。访问未定义name的{foreach}属性不会抛出一个错误,但将导致不可预知的结果。

  • {foreach} properties are indexiterationfirstlastshowtotal.
  • {foreach}属性有index, iteration, first, last, show, total.

Example 7-5. The item attribute
例 7-5. item属性

$arr = array(1000, 1001, 1002);
$smarty->assign('myArray', $arr);

Template to output $myArray in an un-ordered list

{foreach from=$myArray item=foo}

The above example will output:


Example 7-6. Demonstrates the item and key attributes
例 7-6. 演示item和key属性

$arr = array(9 => 'Tennis', 3 => 'Swimming', 8 => 'Coding');
$smarty->assign('myArray', $arr);

Template to output $myArray as key/val pair, like PHP’s foreach.
用模板按键名/键值对的形式输出$myArray, 类似于PHP的foreach。

{foreach from=$myArray key=k item=v}
   <li>{$k}: {$v}</li>

The above example will output:

    <li>9: Tennis</li>
    <li>3: Swimming</li>
    <li>8: Coding</li>

Example 7-7. {foreach} with associative item attribute
例 7-7. {foreach}的item属性是关联数组

$items_list = array(23 => array('no' => 2456, 'label' => 'Salad'),
                    96 => array('no' => 4889, 'label' => 'Cream')
$smarty->assign('items', $items_list);

Template to output $items with $myId in the url

{foreach from=$items key=myId item=i}
  <li><a href="item.php?id={$myId}">{$}: {$i.label}</li>

The above example will output:

  <li><a href="item.php?id=23">2456: Salad</li>
  <li><a href="item.php?id=96">4889: Cream</li>

Example 7-8. {foreach} with nested item and key
例 7-8. {foreach}使用嵌套的item和key
Assign an array to Smarty, the key contains the key for each looped value.

 $smarty->assign('contacts', array(
                             array('phone' => '1',
                                   'fax' => '2',
                                   'cell' => '3'),
                             array('phone' => '555-4444',
                                   'fax' => '555-3333',
                                   'cell' => '760-1234')

The template to output $contact.

{foreach name=outer item=contact from=$contacts}
  <hr />
  {foreach key=key item=item from=$contact}
    {$key}: {$item}<br />

The above example will output:

<hr />
  phone: 1<br />
  fax: 2<br />
  cell: 3<br />
<hr />
  phone: 555-4444<br />
  fax: 555-3333<br />
  cell: 760-1234<br />

Example 7-9. Database example with {foreachelse}
例 7-9. 使用{foreachelse}的数据库示例
A database (eg PEAR or ADODB) example of a search script, the query results assigned to Smarty

  $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}.
借助{foreachelse}标记在没有结果时模板输出”None found”字样。

{foreach key=cid item=con from=$results}
    <a href="contact.php?contact_id={$cid}">{$} - {$con.nick}</a><br />
    No items were found in the search

index contains the current array index, starting with zero.

Example 7-10. index example
例 7-10. index示例

{* The header block is output every five rows *}
{* 每五行输出一次头部区块 *}
{foreach from=$items key=myId item=i name=foo}
  {if $ % 5 == 0}

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

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}

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

Example 7-12. first property example
例 7-12. first属性示例

{* show LATEST on the first item, otherwise the id *}
{* 对于第一个条目显示LATEST而不是id *}
{foreach from=$items key=myId item=i name=foo}
  <td>{if $}LATEST{else}{$myId}{/if}</td>

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

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}
  ... content ...

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 contains the number of iterations that this {foreach} will loop. This can be used inside or after the {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}
{if $}
  <div id="total">{$} items</div>
 ... something else ...

See also {section} and $smarty.foreach.



你必须 登陆 方可发表评论.