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

10,340

Solution 1

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

Solution 2

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

Solution 3

I used the Twig Array Extension, to make use of |shuffle. On my installation the extension wasn't loaded.

Added this to my config/services.yml, under services:

services:
    twig.extension.array:
                class: Twig_Extensions_Extension_Array
                tags: [twig.extension]

Then you can use:

{% for item in items|shuffle %}
    ...
{% endfor %}
Share:
10,340
Run
Author by

Run

A cross-disciplinary full-stack web developer/designer.

Updated on June 13, 2022

Comments

  • Run
    Run almost 2 years

    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.

  • JustOnUnderMillions
    JustOnUnderMillions over 7 years
    No thing, but Twig Array Extension is the better way ;) didnt now it
  • Run
    Run over 7 years
    got it sorted by installing the extensions. thanks! :-)
  • Thomas Kekeisen
    Thomas Kekeisen over 6 years
  • Timurib
    Timurib over 6 years
    Thanks, I fix the anwser!