现在的位置: 首页 > 综合 > 正文

smarty手册-smarty中foreach循环语句详解

2018年01月30日 ⁄ 综合 ⁄ 共 2308字 ⁄ 字号 评论关闭
  • {foreach}循环也有自身属性的变量,可以通过{$smarty.foreach.name.property}访问,其中"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 index, iteration,
    first, last, show, total.
  • {foreach}属性有index, iteration, first, last, show, total.
    Example 7-5. The item attribute

    例 7-5. item属性

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

    Template to output $myArray in an un-ordered list

    用模板以无序列表输出$myArray

    <ul>
    {foreach from=$myArray item=foo}
    <li>{$foo}</li>
    {/foreach}
    </ul>

    The above example will output:

    上例将输出:

    <ul>
    <li>1000</li>
    <li>1001</li>
    <li>1002</li>
    </ul>

    Example 7-6. Demonstrates the item and key attributes

    例 7-6. 演示item和key属性

    <?php
    $arr array(9 => 'Tennis', => 'Swimming', => 'Coding');
    $smarty->assign('myArray', $arr);
    ?>

    Template to output $myArray as key/val pair, like PHP's foreach.

    用模板按键名/键值对的形式输出$myArray, 类似于PHP的foreach。

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

    The above example will output:

    上例将输出:

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

    Example 7-7. {foreach} with associative item attribute

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

    <?php
    $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

    模板中,url通过$myId输出$items

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

    The above example will output:

    上例将输出:

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

    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设置一个数组,对于每个键名对应的每个循环值都包括键。

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

抱歉!评论已关闭.