tags:

views:

52

answers:

3

Im using the following Smarty code:

{foreach from=$entries key=i item=topic}
  {if $topic.topic_style == question}
    <li>
      <a href="topic.php?id={$topic.id}">{$topic.title}</a>
    </li>
  {/if}
{/foreach}

How can i do the {foreach} a maximum of 10 times and then stop?

A: 

Use index:

{foreach from=$entries key=i item=topic name=foo}
  {if $smarty.foreach.foo.index < 10}
    {if $topic.topic_style == question}
      <li>
        <a href="topic.php?id={$topic.id}">{$topic.title}</a>
      </li>
    {/if}
  {/if}
{/foreach}
Dominic Rodger
+2  A: 

You can use index and break function:

{foreach from=$entries key=i item=topic name=foo}
  {if $smarty.foreach.foo.index == 10}
    {break}
  {/if}
  {if $topic.topic_style == question}
    <li>
      <a href="topic.php?id={$topic.id}">{$topic.title}</a>
    </li>
  {/if}
{/foreach}

Break function is described here:

http://stackoverflow.com/questions/2116391/break-in-smartys-dwoos-foreach

hsz
A: 

If you don't want to write smarty plugin, you can do this too:

{foreach from=$entries key=i item=topic name=foo} 
  {if $smarty.foreach.foo.index == 10} 
       {php}break;{/php}    
  {/if} 
  {if $topic.topic_style == question} 
    <li> 
      <a href="topic.php?id={$topic.id}">{$topic.title}</a> 
    </li> 
  {/if} 
{/foreach} 
Zsolti