Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Smarty foreach counter , reset after 3 element

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 ?

like image 465
woj_jas Avatar asked Nov 01 '14 10:11

woj_jas


4 Answers

{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

like image 64
Aleksandar Vasić Avatar answered Oct 03 '22 21:10

Aleksandar Vasić


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 ;)

like image 37
Maciej Avatar answered Oct 03 '22 21:10

Maciej


Try like

{if $counter%3 eq 0 && $counter gt 2}
    {assign var=counter value=1}
{/if}
like image 45
Gautam3164 Avatar answered Oct 03 '22 22:10

Gautam3164


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}
like image 36
Jeff B Avatar answered Oct 03 '22 20:10

Jeff B