2012-06-17 62 views
2

我想用smarty實現這樣的列表。Smarty - foreach循環4次並創建一個新列表

<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>。然後,當它達到第四個索引時,它將創建一個新的<li>標籤。

感謝您的幫助!

回答

2

林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 [email protected]} 
    <ul> 
     <li> 
    {elseif ([email protected] - 1) is div by 4} 
     </li><li> 
    {/if} 

    <span>{$value}</span> 

    {if [email protected]} 
     </li> 
    </ul> 
    {/if} 
{/foreach} 

注意,因爲foreach循環嵌套在整個<ul>的,它不會顯示如果沒有數據遍歷。

+0

真棒這個作品!謝謝! – Harold

+0

迭代-1爲什麼不只是使用索引? –

+1

因爲你可能正在迭代一個不適用於索引的映射(關聯數組/字符串鍵)。 – rodneyrehm

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>