Smarty - foreach循环4次并创建一个新列表

时间:2012-06-17 08:54:39

标签: php html smarty

我想用smarty来实现这样的列表。

<ul>
 <li>
   <a>img1</a>
   <a>img2</a>
   <a>img3</a>
   <a>img4</a>
 </li>
 <li>
   <a>img5</a>
   <a>img6</a>
   <a>img7</a>
   <a>img8</a>
 </li>
<li>
   <a>img9</a>
   <a>img10</a>
   <a>img11</a>
   <a>img12</a>
 </li>
</ul>

使用此示例代码

<ul class="bullet">
    {foreach from=$manufacturers item=manufacturer name=manufacturer_list}
        {if $smarty.foreach.manufacturer_list.index < 4}
      <li class="{if $smarty.foreach.manufacturer_list.last}last_item{elseif $smarty.foreach.manufacturer_list.first}first_item{else}item{/if}">   

        <a href="{$link->getmanufacturerLink($manufacturer.id_manufacturer, $manufacturer.link_rewrite)}" title="{l s='More about' mod='blockmanufacturer'}{$manufacturer.name}"> <img src="{$img_manu_dir}{$manufacturer.id_manufacturer}.jpg"><span>{$manufacturer.name}<span></a>
      </li>
    {/if}
{/foreach}

首先,对于给定的数组$制造商,它将在<li>最多4次内循环并创建4 <img>。然后,当它达到第4个索引时,它将生成一个新的<li>标记。

感谢您的帮助!

2 个答案:

答案 0 :(得分:5)

您希望在每个li标签中显示4张图片吗?

<ul>
{foreach from=$manufacturers item=manufacturer name=manufacturer_list}
  {if $smarty.foreach.manufacturer_list.index % 4 == 0}
    <li>
  {/if}

  <a><img></a>

  {if $smarty.foreach.manufacturer_list.index % 4 == 0 || $smarty.foreach.manufacturer_list.last}
    </li>
  {/if}
{/foreach}
</ul>

答案 1 :(得分:2)

Im Smarty3语法你可以做类似的事情:

{$data = [
    "alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", 
    "hotel", "india", "juliet", "kilo", "lima", "mike", "november", 
    "oscar", "papa", "quebec", "romeo", "sierra", "tango", "uniform", 
    "victor", "whiskey", "x-ray", "yankee", "zulu"
]}

{foreach $data as $value}
  {if $value@first}
    <ul>
      <li>
  {elseif ($value@iteration - 1) is div by 4}
      </li><li>
  {/if}

  <span>{$value}</span>

  {if $value@last}
      </li>
    </ul>
  {/if}
{/foreach}

请注意,由于将整个<ul>嵌套在foreach循环中,因此无法显示是否没有要循环的数据。