foreach can be used equal to for

解决方案 »

  1.   

    实在需要的话可以考虑自己给smarty加一个for。我的smarty就自己加了for和数组汉字下标的支持。
      

  2.   

    打开文件<Smarty_Compiler.class.php>
    查找函数: function _compile_tag($template_tag)
    往下拉,找到这个函数里的第一个switch,添加for和/for。如下。
            switch ($tag_command) {
    case 'for':
    $this->_push_tag('for');
    return $this->_compile_for_start($tag_args);
    case '/for':
    $this->_pop_tag('for');
    return "<?php endfor; ?>";
                case 'include':
                    return $this->_compile_include_tag($tag_args);最后再添加for的处理函数,将以下函数加到class smarty里:
        function _compile_for_start($tag_args)
    {
            $attrs = $this->_parse_attrs($tag_args);
            $arg_list = array();        if (empty($attrs['name'])) {
                return $this->_syntax_error("for: missing 'name' attribute", E_USER_ERROR, __FILE__, __LINE__);
            }
            if (!isset($attrs['from'])) {
                return $this->_syntax_error("for: missing 'from' attribute", E_USER_ERROR, __FILE__, __LINE__);
            }
            if (!isset($attrs['to'])) {
                return $this->_syntax_error("for: missing 'to' attribute", E_USER_ERROR, __FILE__, __LINE__);
            }
    return "<?php for(\$this->_tpl_vars[{$attrs['name']}]={$attrs['from']};\$this->_tpl_vars[{$attrs['name']}]<={$attrs['to']};\$this->_tpl_vars[{$attrs['name']}]++): ?>";
    }
    -------------------------------
    大功告成。试一试
    {for name=i from=1 to=8}
    <td> 第{$i}行 *** </td>
    {/for}
      

  3.   

    当然如果你不打算有for嵌套的话,可以用register_block来实现for的功能。毕竟自己修改smarty的原码会对后续接手你程序的人产生一定困惑。哎,哪来的for
      

  4.   

    主要是用section和foreach都得生成一个多余的数组。用起来就不太爽。
    for还是有一定的要求的。我估计后几个版本smarty还是会把它加上。
      

  5.   

    不过for是为我这样的懒人用的。smarty推荐的办法是copy copy copy
      

  6.   

    什么叫多余的数组啊 section 也可以限制循环多少次啊 section里的name 和for 里的$i 有啥区别么 感觉section更好用$smarty.section.i.index 其实就是楼上楼上几个楼上中所说的for 中的$i 多看看手册吧 SMARTY很强大的 强大的对俺来说都多余所以俺不喜欢用smarty了
      

  7.   

    同志。section的loop是必要参数。也就是说你打印0到1000的数字出来,你就得建一个下标长度为1000的数组。这不叫多余数组叫什么?
      

  8.   

    我不知道你现在用的什么版本的smarty。我也不可能天天去盯着smarty的新版。我觉得for的功能肯定会加进smarty的,另开for还是用secion实现罢了。
    以此为例
    {for name=i from=1 to=1000}
    {$i}
    {/for}在我现在用的2.6.10版里。如果不指定一个长度为1000的数组做为loop的话,以下语句是什么也不会输出的!我就得多建一个无用的长度为1000的数组。
    {section name=i start=1 max=1000 loop=$nothing}
    {%i.index%}
    {/section}