Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig - How to randomise items in the array and loop them?

How can I randomise items in the array and loop them?

{% for item in article.resources|shuffle|slice(1) %}
    ...
{% endfor %}

I get this error:

Unknown "shuffle" filter in "partials/content.twig" at line 30.

If I use random():

{% for item in random(article.resources|slice(1)) %}

Nothing is returned.

Any ideas?

NOTES:

I don't want to use PHP btw.

like image 542
Run Avatar asked Dec 19 '22 11:12

Run


2 Answers

Twig Array Extension already has a shuffle() filter (based on PHP shuffle())

like image 52
Timurib Avatar answered Jan 04 '23 23:01

Timurib


Do something like that:

$twig = new Twig_Environment($loader);
$function = new Twig_SimpleFunction('shuffle', function ($array) {
    shuffle($array);
    return $array;
});
$twig->addFunction($function);

read more about it here

http://twig.sensiolabs.org/doc/advanced.html#functions

like image 39
JustOnUnderMillions Avatar answered Jan 04 '23 23:01

JustOnUnderMillions