2011-01-05 111 views
13

我通常不是Smarty的傢伙,所以我有點卡住了。如何增加Smarty變量?

我想回顯數組的索引,但我想每次回顯時都增加它。

這是我...

<ul> 
    {foreach from=$gallery key=index item=image} 
    <li> 
     <img src="{$image}" alt="" id="panel-{$index++}" /> 
    </li> 
    {/foreach} 
</ul> 

它不工作。

在將它交給Smarty之前,這樣做是預處理數組的最佳方法嗎?

有沒有一種方法可以使用Smarty來做到這一點?

+2

但因爲你從foreach循環得到'index',你的意思是它實際上只是1? – mario 2011-01-05 02:12:01

+0

@mario是的,這就是我想要的。 – alex 2011-01-05 03:17:19

+0

您也可以使用'{counter start = 1}'來代替索引。 – mario 2011-01-05 03:24:05

回答

23

你可以做類似如下:

<ul> 
    {foreach from=$gallery key=index item=image name=count} 
    <li> 
     <img src="{$image}" alt="" id="panel-{$smarty.foreach.count.index}" /> 
    </li> 
    {/foreach} 
</ul> 

從零開始,index是當前數組索引。

這可能去了解它的最佳方式,但是,簡單地用一個counterforeach循環,你可以用counter,像這樣:

{counter start=0 skip=1 assign="count"} 

爲了增加它只需撥打{counter}在每次迭代。

{counter} 
{*Can then use the $count var*} 
    {if $count is div by 4} 
     {*do stuff*} 
    {/if} 
+1

+1謝謝羅素! – alex 2011-01-05 03:21:34

+0

如果我需要增加和減少櫃檯會怎麼樣? – Gio2k 2011-08-02 14:55:18

+0

如果你在頁面上有多個foreach,怎麼辦?計數將從「0」開始。 – karadayi 2015-03-02 13:19:37

0

$index++會不會在回聲後遞增?

try ++$index;或做$index++之前你回聲它。

3

如果是智者2(從在foreach語法你使用它看起來像)你可以給foreach循環的名稱,然後使用{$smarty.foreach.name.index}

像這樣

<ul> 
    {foreach from=$gallery key=index item=image name=foo} 
    <li> 
     <img src="{$image}" alt="" id="panel-{$smarty.foreach.foo.index}" /> 
    </li> 
    {/foreach} 
</ul> 

該指數開始在零,如果你想要一個序列,從1開始使用.iteration而不是.index

我還沒有用過smarty很長一段時間了,但我總是發現很多例子的官方文檔非常好http://www.smarty.net/docsv2/en/language.function.foreach.tpl

0

假設你通過$ foo的其是與索引和迭代選項

{foreach from=$foo item=bar name=humbug} 
    {$smarty.foreach.humbug.index} 
    {$smarty.foreach.humbug.iteration} 
{/foreach} 

第一列是索引結果的陣列運行時,第二列是迭代結果

0 - 1 
1 - 2 
2 - 3 
3 - 4 
4 - 5 

這意味着索引從0開始作爲其數組索引,其中迭代是從1開始的循環迭代計數。

使用錯誤值會導致問題的實例是在表格中顯示4行或其他任何數量的行。

使用索引會導致表格佈局錯誤。您將在循環的第一次迭代(索引0)上立即進行行更改,這將在第5次迭代(索引4)處自行糾正,但僅在當前佈局的範圍內,這意味着您的第一行只有1個單元格它。每隔一行將有4個單元格,並且在第一行之後的每個單元格中的數據將出現在表格4單元格中,比它應該做的晚。

{if $smarty.foreach.humbug.index is div by 4} 
    </tr><tr> 
{/if} 

使用迭代將鋪陳行更改正確給人4等於行,直到最後一次迭代或foreach循環。

{if $smarty.foreach.humbug.iteration is div by 4} 
</tr><tr> 
{/if} 

在foreach循環之後,您只需簡單地添加一個表格行來完成最後一行。

我希望這可以幫助別人。

0
{foreach from=$foo item=bar name=humbug} 
{$smarty.foreach.humbug.index} 
{$smarty.foreach.humbug.iteration} 
{/foreach} 

{foreach from=$foo item=bar name=berlin} 
{$smarty.foreach.berlin.index} 
{$smarty.foreach.berlin.iteration} 
{/foreach} 
0

您可以使用{counter}

{counter}用來打印出一個計數。 {counter}將記住每次迭代中的 計數。您可以調整數量,間隔以及計數的方向,以及確定是否以 的值打印。您可以通過 同時運行多個計數器,爲每個計數器提供一個唯一的名稱。如果不提供名稱,該名稱 「默認」將被用來

來源:http://www.smarty.net/docsv2/en/language.function.counter.tpl

用法:

{counter start=0 print=false assign="count"} 

<ul> 
{foreach from=$listing.products item="product"} 
    {counter} 
    {if $count === 1} 
    <p>Count is 1</p> 
    {/if} 
{/foreach} 
</ul>