[转]Smarty模板中for循环的扩展

近两年来,一直在使用Smarty模板做php系统的开发,感觉效率非常高。但是随着使用的增多,也出现了一些不方便的地方,或者需要解决的难题,今后我会把这些问题的解决慢慢写上来和大家分享。

今天的这个问题可能也困扰了很多人,它说简单很简单,但是smarty中就是没有一个解决的方案,我上网搜了一下,也是没有满意的答案,而且大部分都是答非所问。

先来看问题:
需要能在Smarty模板文件中循环$sCount变量,就像类似于下面的PHP循环形式:

for ($i = 0; $i < $sCount; $i++)
{
......
}

但是又不使用{php}。。。{/php}标签。Smarty中的循环无论foreach还是section全部都是关于数组循环的语句,要想循环,就必须在php文件中先建立一个数据组。而且有的时候,这个数组的元素数量是不定的。这就给开发人员带来的多出一倍的代码量。

考察了smarty文档后,发现可以用自定义的plugin来解决这个问题,于是就动手写了一个。

plugin文件:

<?php



function smarty_block_for($params, $content, &$smarty)
{
    if (is_null($content)) {
        return;
    }

    $from = 0;
    $to = 0;
    $step = 1;
   
    foreach ($params as $_key => $_val) {
        switch ($_key) {
            case 'from':
            case 'to':
            case 'step':
                $$_key = (int)$_val;
                break;

            default:
                $smarty->trigger_error("textformat: unknown attribute '$_key'");
        }
    }

    $_output = '';

    for($_x = $from; $_x <= $to; $_x += $step) {
        $_output .= $content."\n\r";
    }

    return $_output;

}

?>

把上面的内容复制到一个php文件中,文件名保存为“block.for.php”

然后把这个文件复制到smarty模板的安装目录下的plugins文件夹中即可。

在模板文件中的用法:

{for start = 1 to = 5 step = 1}
...要循环的html内容...
{/for }>

循环次数为 (to - start + 1) / step
原文地址:https://www.cnblogs.com/luowei/p/2436586.html