Smarty - foreach loop 10 times and stop

Viewed 49180

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?

8 Answers

All the above worked to a certain degree, but not exactly what I wanted. Here's what worked for me. I basically used the index property of foreach

{foreach $products as $product}
{if $product@index eq 3}
    {break}
{/if}
<img src="..products/{$product.product_image}" alt="">

{/foreach}

Small extend in smarty to limit foreach.

On file : sysplugins/smarty_internal_compile_foreach.php

Add limit to original attributes :

public $optional_attributes = array('name', 'key','limit'); 

Add after $output = "<?php "; this >

if (isset($_attr['limit'])) {
    $limit = $_attr['limit'];
    $output .= "\n \$_limitCnt = 0; \n \$_limit = $limit; \n";
}

Add before $output .= "?>"; this >

if (isset($_attr['limit'])) {
     $output .= "\n if (\$_limitCnt == \$_limit) { break; }";
     $output .= "\n \$_limitCnt++;";
}

Use as usuall for each and add limit=# to limit your results.

Hope i helped.

Related