alexsm alexsm - 4 months ago 38
Smarty Question

Smarty foreach / shuffle/random and limit

I want to get items foreach, shuffle them and limit the output to 4 items.

i've this. (displays all items)

{content block_id=27}
{if $_content_27|count >0}
{foreach name=aussen item=box_data from=$_content_27}
<article class="news_row_article col-lg-3">
<div><img src="images/ImgResponsive_Placeholder.png" alt=""/></div>
<h3 class="news_row_headline">{$box_data.content_heading}</h3>
<p class="news_row_content">{$box_data.content_body}</p>
</article>
{/foreach}
{/if}


i've found this

{foreach array_rand($a_firm_display,5) as $i}
<a href="{$smarty.const.HOST}{$a_firm_display[$i].url_rewriting}"><img src="{$a_firm_display[$i].firm_logo}" /></a>
{/foreach}


or this
Generate distinct smarty random numbers

{assign var="distinct_numbers" value=array_fill(1,15,'x')}
{assign var="distinct_numbers" value=array_keys($distinct_numbers)}
{assign var="x" value=shuffle($distinct_numbers)}

{* result *}

{foreach from=$distinct_numbers item="value"}
{$value} |
{/foreach}


hm..somehow get the items from $_content_27 put them into array, output, and limit them ?

any ideas ?

Answer

Maybe you can use shuffle and for instead of foreach, if you don't mind losing the array keys:

{$_content_27=$_content_27|@shuffle}
{for $iter=0 to 3}
    ...
    {$_content_27.$iter.content_heading}
    ...
{/for}