4

如何随机化数组中的项目并循环它们?

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

我收到此错误:

第 30 行“partials/content.twig”中的未知“shuffle”过滤器。

如果我使用random()

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

什么都没有返回。

有任何想法吗?

笔记:

我不想使用 PHP 顺便说一句。

4

4 回答 4

6

Twig Array Extension已经有一个shuffle()过滤器(基于PHP shuffle()

于 2016-11-16T10:36:17.397 回答
3

做这样的事情:

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

在此处阅读更多信息

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

于 2016-11-16T10:36:41.887 回答
2

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 %}
于 2018-03-07T10:04:15.807 回答
0

我认为你将不得不删除它的切片部分。

试试这个代码,让我知道这是否有效。

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

{% endfor %}

您可能希望在 for 循环中进行一些检查,以确保 random 不会两次返回相同的项目。

于 2016-11-16T10:19:02.067 回答