0

How can I limit the amount of loops through an array using Smarty? Let's say that there's 32 items in a given array, I'd like to limit the number of loops to 8.

{foreach from=$friend_list key=userId item=userInfo name=friend_list}
    {if $smarty.foreach.friend_list.index % 8 && $smarty.foreach.friend_list.index > 0 }
        </tr><tr>
    {/if}
        <td height='50' width='50'>
            <img border='0' height='50' src='http://graph.facebook.com/{$userInfo.user_uid}/picture' style='display:block;' width='50' />
        </td>
{/foreach}

Thanks

conbask
  • 9,741
  • 16
  • 57
  • 94

3 Answers3

1
{foreach from=$friend_list key=userId item=userInfo name=friend_list}
  {if $smarty.foreach.friend_list.index < 8 }
    {if $smarty.foreach.friend_list.index % 8 && $smarty.foreach.friend_list.index > 0 }
        </tr><tr>
    {/if}
        <td height='50' width='50'>
            <img border='0' height='50' src='http://graph.facebook.com/{$userInfo.user_uid}/picture' style='display:block;' width='50' />
        </td>
  {/if}
{/foreach}

Read this Smarty - foreach loop 10 times and stop

ps: I intentionally left the if block with if $smarty.foreach.friend_list.index % 8 in case if will need more than 8 loops. Otherwise that block could be removed (keeping </tr><tr> intact)

Community
  • 1
  • 1
Cheery
  • 16,063
  • 42
  • 57
0

add a counter before you open you foreach,

$i=1;

increase the counter on each loop (ie inside the foreach)

if($i = 8) break; 
$i++;

(where 8 is your limit)

you code looks all wrong so I didnt bother placing it in. Sort out the () {} issues

Nick
  • 908
  • 12
  • 29
  • oh wait up, this is inside the smarty template right? why place so much logic in the presentation layer? wouldn't this be better in the PHP? – Nick Feb 03 '12 at 01:49
0

Here, that should process the first 8 entries and ignore the rest. Unfortunately, there's no way to break from a Smarty for each.

{foreach from=$friend_list key=userId item=userInfo name=friend_list}
    {if $smarty.foreach.friend_list.iteration < 8}
        <td height='50' width='50'>
            <img border='0' height='50' src='http://graph.facebook.com/{$userInfo.user_uid}/picture' style='display:block;' width='50' />
        </td>
    {/if}
{/foreach}
Simon Germain
  • 6,834
  • 1
  • 27
  • 42