PHP:如何使用smarty部分进行以下输出?

时间:2014-07-03 05:09:01

标签: php foreach smarty

我正在使用偶数和奇数逻辑,但没有得到我需要的输出

例如我有

数组
$data = array(1000,1001,1002, 1003,1004,1005);
$smarty->assign('data',$data);

{section name=i loop=$data}

{section}

所以我需要的输出是:

<div>
    <dl>1000</dl>
    <dl>1001</dl>
</div>

<div>
    <dl>1002</dl>
    <dl>1003</dl>
</div>

<div>
    <dl>1004</dl>
    <dl>1005</dl>
</div>

2 个答案:

答案 0 :(得分:0)

根据官方文件http://www.smarty.net/docsv2/en/language.function.section.tpl

请尝试以下代码:

<div>
{section name=i loop=$data}

       <dl>{$data[i]}</dl>

   {if $smarty.section.data.index > 0 && $smarty.section.data.index % 2 == 0 && $smarty.section.data.index < $smarty.section.customer.total -1}
      </div><div>
   {/if}

{/section}
</div>

答案 1 :(得分:0)

你应该这样做:

{section name=i loop=$data}
    {if $smarty.section.i.index %2 == 0}
        <div>
    {/if}
       <dl>{$data[i]}</dl>
    {if $smarty.section.i.index %2 == 1 || $smarty.section.i.last}
        </div>
    {/if}
{/section}
应该在部分中创建

<div>,因为当没有任何项目时,您可能不想创建空<div>。如果您有5个元素,则会添加最后一个条件$smarty.section.i.last,在这种情况下,您当然要确保您的div已关闭。