Smarty plural list

Is there any smart way to send random numbers (e.g. 1-4) to a list using smarty tpl-engine?

standard list sorted 1-5:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
</ul>

Here is my solution (PHP):

<ul>
{foreach from=randomNumbers}
<li>{smarty.randomNumbers}</li>
{/foreach}
</ul>

modified list sorted 1-5 (random):

<ul>
  <li>3</li>
  <li>2</li>
  <li>5</li>
  <li>1</li>
  <li>4</li>
</ul>

I really tested almost everything, but for this I need only a small and small solution :-)

Regards, Heinrich

+3
source share
3 answers

You can use the rand () function from php in smarty. Pass the parameter as the number of times you run the loop, and you have to do it.

+1
source

You could do something really dirty like this:

<ul>
  {foreach from=0|range:4|@array_rand:5 item=i}
    {assign var=i value=$i+1}
    <li>{$i}</li>
  {/foreach}
</ul>

Strike> Edit

, array_rand() . shuffle() , - - :

//somewhere in an included PHP file
function shuffle_array($array){ 
   shuffle($array);
   return $array;   
}

{*template *}
<ul>
  {foreach from=1|range:5|@shuffle_array item=i}
    <li>{$i}</li>
  {/foreach}
</ul>
+1

OK, this seems to be a PHP problem. Since the latest versions of PHP, array_rand is not random. I tried to add something like this

    |shuffle

or

    shuffle();

to tom smarty-code,

but without success> _ <

...

0
source

Source: https://habr.com/ru/post/1740145/


All Articles