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

给你一囗甜甜゛ 提交于 2019-12-05 14:23:13

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

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

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 %}

I think you will have to remove slice part of it.

Try this code and let me know if this works.

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

{% endfor %}

You would probably like to keep some check in your for loop to ensure random is not returning same item twice.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!