Search code examples
phpsmarty

Smarty counter variable define in parent file but increment and using inside child includ file


I like to define a counter variable in parent tpl file (First.tpl) and increment and using it inside child include file (Second.tpl).

But the counter does not increase anymore.

First.tpl:

{assign var = "counter" value = 1 scope = "global"}
{foreach ...} //iterates at least 100 times
  {include file='Second.tpl'}
{/foreach}

Second.tpl:

{assign var="counter" value = $counter+1}
{$counter} //counter does not increase!

{if $counter > 10} do-something {/if} // if statement fails always!

Solution

  • This is the way I use to do something like that, increasing the value inside the loop, and passing the value to the included file. Try it:

    First.tpl

    {assign var="counter" value=0}
    {foreach ...} /* iterates at least 100 times */
        {assign var="counter" value=$counter+1}
        {include file='Second.tpl' counter=$counter}
    {/foreach}
    

    Second.tpl

    {$counter} /* Check if counter increase */
    
    {if $counter > 10} do-something {/if}
    

    Note.- I initialized $counter to zero.