I want to create foreach smarty loop with counter and 3 "if" conditions inside. After my counter value is more than 3 I want to reset counter value and get back to first condition of If
This is my code
{foreach $itemscollection as $singleitem name=smartyloop}
{assign var="counter" value=$smarty.foreach.smartyloop.iteration}
{if $counter == 1}
<h1>I am the one</h1>
{/if}
{if $counter == 2}
<h1>I am second</h1>
{/if}
{if $counter == 3}
<h1>I am third</h1>
{/if}
{if $counter > 3}
{$counter = 1}
{/if]
{/foreach}
So for example If I have 4 elements to place into foreach output should look like
I am the one
I am second
I am third
I am the one
Now it's not working and i don't know why. Can somebody please help me and tell how to resolve that problem ?
{assign var=counter value=1}
{foreach $itemscollection as $singleitem name=smartyloop}
{if $counter == 1}
<h1>I am the one</h1>
{/if}
{if $counter == 2}
<h1>I am second</h1>
{/if}
{if $counter == 3}
<h1>I am third</h1>
{/if}
{if $counter > 3}
{assign var=counter value=1}
{/if]
{$counter++}
{/foreach}
this might work
I know this is an old one but try to use counter as a custom function from smarty:
{foreach $itemscollection as $singleitem name=smartyloop}
{counter assign='pos'} {* assign counter to variable *}
{if $pos == 1}
<h1>I am the one</h1>
{/if}
{if $pos == 2}
<h1>I am second</h1>
{/if}
{if $pos == 3}
<h1>I am third</h1>
{counter start=0} {*reset counter*}
{/if}
{/foreach}
Had to go back to CMS Made Simple to make something related ;)
Try like
{if $counter%3 eq 0 && $counter gt 2}
{assign var=counter value=1}
{/if}
You can use {cycle} http://www.smarty.net/docs/en/language.function.cycle.tpl
{cycle name="counter" values="1,2,3"}
Or you could use the Modulus(%) operator http://php.net/manual/en/language.operators.arithmetic.php
{$counter = ($smarty.foreach.smartyloop.iteration % 3) + 1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With