【问题标题】:PHP : How to use smarty section for the following output?PHP:如何使用 smarty 部分进行以下输出?
【发布时间】:2014-07-03 05:09:00
【问题描述】:

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

例如我有一个数组

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

【问题讨论】:

  • 因为我在 smarty 中使用它,所以我需要部分
  • 尝试使用step=2参数然后{$data[i]}, {$data[i+1]}

标签: php foreach smarty


【解决方案1】:

根据官方文档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>

【讨论】:

  • 最后一个 div 为空,是否还需要应用最后一个条件 {if $smarty.section.i.iteration > 0 && $smarty.section.i.iteration % 2 == 0 } {if $smarty.section.i.last neq $smarty.section.i.iteration}
    {/if} {/if}
  • @khanAsim 更新了兄弟
【解决方案2】:

你应该这样做:

{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}

&lt;div&gt; 应该在部分中创建,因为当没有任何项目时,您可能不想创建空的&lt;div&gt;。最后一个条件 $smarty.section.i.last 添加以防万一您有 5 个元素,在这种情况下,您当然要确保您的 div 已关闭。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-07
    • 2021-10-03
    相关资源
    最近更新 更多